Skip to content

Instantly share code, notes, and snippets.

Last active May 22, 2022 09:43
What would you like to do?
Exception handler for both python2 and python3
from sys import exc_info, version_info
from os.path import abspath
blue = "\033[0;34m"
white ="\033[0;37m"
red = "\033[0;31m"
error = "{}[{}!{}] {}".format(blue, white, blue, red)
def exception_handler(e, multiline=False):
lines_arr = []
exc_type, exc_value, exc_traceback = exc_info()
if version_info[0] == 3:
tb = e.__traceback__
filename = abspath(__file__)
if version_info[0] == 2:
tb = exc_traceback
filename = __file__
while tb is not None:
if tb.tb_frame.f_code.co_filename == filename:
tb = tb.tb_next
name = type(e).__name__
if str(e).find(":")!=-1:
message = str(e).split(":")[0]
elif str(e).find("(")!=-1:
message = str(e).split("(")[0]
message = str(e)
line_no = lines_arr[len(lines_arr) - 1]
lines_no = ", ".join(lines_arr)
if multiline:
print("{}{}: {} at lines {}".format(error, name, message, lines_no))
print("{}{}: {} at line {}".format(error, name, message, line_no))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment