How to get Python exception text?

PythonServer Side ProgrammingProgramming

If a python code throws an exception, we can catch it and print the type, the error message, traceback and get information like file name and line number in python script where the exception occurred.

We can find the type, value, traceback parameters of the error

Type gives the type of exception that has occurred; value contains error message; traceback contains stack snapshot and many other information details about the error message.

The sys.exc_info() function returns a tuple of these three attributes, and the raise statement has a three-argument form accepting these three parts.

Getting exception type, file number and line number in sample code

import sys, os
raise NotImplementedError("No error")
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno

Published on 06-Dec-2017 13:18:07