Last updated: Apr 12, 2024
Reading time·5 min

To get the type, file and line number of an exception in Python:
sys.exc_info() method to get the exception type, object and
traceback.import sys import os try: raise ValueError('invalid value') except ValueError as e: e_type, e_object, e_traceback = sys.exc_info() e_filename = os.path.split( e_traceback.tb_frame.f_code.co_filename )[1] e_message = str(e) e_line_number = e_traceback.tb_lineno print(f'exception type: {e_type}') print(f'exception filename: {e_filename}') print(f'exception line number: {e_line_number}') print(f'exception message: {e_message}')
Running the code sample produces the following output.
exception type: <class 'ValueError'> exception filename: main.py exception line number: 5 exception message: invalid value

The sys.exc_info() method returns the old-style representation of the handled exception.
import sys try: raise ValueError('invalid value') except ValueError as e: # (<class 'ValueError'>, ValueError('invalid value'), <traceback object at 0x7fd0f0b427c0>) print(sys.exc_info())
The tuple contains the exception type, the exception object and the exception traceback.
The exception type is a subclass of BaseException.
The second element of the tuple is the exception object itself (same as e).
The third element is a traceback object which contains information about at what point the exception occurred.
You have to make sure to use the sys.exc_info() method in an except block.
None values.As shown in the code sample, you can use the traceback object to get:
import sys import os try: raise ValueError('invalid value') except ValueError as e: e_type, e_object, e_traceback = sys.exc_info() e_filename = os.path.split( e_traceback.tb_frame.f_code.co_filename )[1] e_message = str(e) e_line_number = e_traceback.tb_lineno print(f'exception type: {e_type}') print(f'exception filename: {e_filename}') print(f'exception line number: {e_line_number}') print(f'exception message: {e_message}')
Running the code sample produces the following output.
exception type: <class 'ValueError'> exception filename: main.py exception line number: 5 exception message: invalid value

traceback.format_exc()You can also use the traceback.format_exc() method to get the type, file and line number of an exception.
import traceback try: raise ValueError('invalid value') except ValueError as e: print(traceback.format_exc())
Running the code sample produces the following output.
Traceback (most recent call last): File "/home/borislav/Desktop/bobbyhadz_python/main.py", line 4, in <module> raise ValueError('invalid value') ValueError: invalid value

As shown in the output, the name of the file (the absolute path) is shown on the second line.
File "/home/borislav/Desktop/bobbyhadz_python/main.py", line 4, in <module>
The message also contains the line on which the exception was raised in said file.
The next line shows the specified line.
raise ValueError('invalid value')
The last line shows the type of the error and the message.
ValueError: invalid value
You can achieve the same result by using the traceback.print_exc method.
import traceback try: raise ValueError('invalid value') except ValueError as e: traceback.print_exc()
Running the code sample produces the following output.
Traceback (most recent call last): File "/home/borislav/Desktop/bobbyhadz_python/main.py", line 4, in <module> raise ValueError('invalid value') ValueError: invalid value

You can also get the type, file and line number of an exception without any imports.
Here is an example that accesses the attributes directly on the exception object.
try: raise ValueError('invalid value') except ValueError as e: e_type = type(e).__name__ e_file = e.__traceback__.tb_frame.f_code.co_filename e_line = e.__traceback__.tb_lineno e_message = str(e) print(f'exception type: {e_type}') print(f'exception filename: {e_file}') print(f'exception line number: {e_line}') print(f'exception message: {e_message}')
Running the code sample produces the following output.
exception type: ValueError exception filename: /home/borislav/Desktop/bobbyhadz_python/main.py exception line number: 2 exception message: invalid value

As shown in the code sample, you can access the __name__ attribute to get the
exception type directly in the except block.
try: raise ValueError('invalid value') except ValueError as e: # ValueError e_type = type(e).__name__
Getting the absolute path to the file in which the exception occurred can also be done by using the attributes on the exception object.
try: raise ValueError('invalid value') except ValueError as e: # exception filename: /home/borislav/Desktop/bobbyhadz_python/main.py e_file = e.__traceback__.tb_frame.f_code.co_filename
The same is the case for retrieving the line on which the exception occurred.
try: raise ValueError('invalid value') except ValueError as e: # 👇️ 2 e_line = e.__traceback__.tb_lineno
If you want to convert the exception object to a string to get the error message, use the str class.
try: raise ValueError('invalid value') except ValueError as e: # invalid value e_message = str(e)
If you need to get the type, file and line number of multiple (all) exceptions
that have occurred, use a while loop.
try: raise ValueError('invalid value') except ValueError as e: all_exceptions = [] tback = e.__traceback__ while tback is not None: e_type = type(e).__name__ e_file = tback.tb_frame.f_code.co_filename e_line = tback.tb_lineno e_message = str(e) all_exceptions.append({ 'e_type': e_type, 'e_file': e_file, 'e_line': e_line, 'e_message': e_message, }) tback = tback.tb_next print(all_exceptions)
Running the code sample produces the following output.
[{'e_type': 'ValueError', 'e_file': '/home/borislav/Desktop/bobbyhadz_python/main.py', 'e_line': 2, 'e_message': 'invalid value'}]

We used a while loop to iterate for as long as the tback variable doesn't
store a None value.
On each iteration, we append a dictionary containing the exception details to the list.
Once the exception details are added to the list of dictionaries, we reassign
the tback variable to the next exception in the stack.
You can learn more about the related topics by checking out the following tutorials: