Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to get Python exception text?

In python code, how do I access/get the python exception text or message or information like the filename and line number where the exception occurred?


1 Answer
Rajendra Dharmkar

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
try:
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

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.