Python: Get the Type, File and Line Number of Exception

avatar
Borislav Hadzhiev

Last updated: Apr 12, 2024
5 min

banner

# Table of Contents

  1. Python: Get the Type, File and Line Number of Exception
  2. Python: Get the Type, File and Line Number of Exception using traceback.format_exc()
  3. Python: Get the Type, File and Line Number of Exception without any imports
  4. Getting the Type, File and Line Number of multiple exceptions

# Python: Get the Type, File and Line Number of Exception

To get the type, file and line number of an exception in Python:

  1. Use the sys.exc_info() method to get the exception type, object and traceback.
  2. The exception filename and line number can be accessed on the traceback object.
main.py
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}')
The code for this article is available on GitHub

Running the code sample produces the following output.

shell
exception type: <class 'ValueError'> exception filename: main.py exception line number: 5 exception message: invalid value

get type file and line number of exception in python

The sys.exc_info() method returns the old-style representation of the handled exception.

main.py
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.

If the method is used when no exception is being handled on the stack, it returns three None values.

As shown in the code sample, you can use the traceback object to get:

  • the filename - the name of the file in which the exception occurred.
  • the line number - on which line in the file the exception was last raised.
main.py
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}')
The code for this article is available on GitHub

Running the code sample produces the following output.

shell
exception type: <class 'ValueError'> exception filename: main.py exception line number: 5 exception message: invalid value

get type file and line number of exception in python

# Python: Get the Type, File and Line Number of Exception using traceback.format_exc()

You can also use the traceback.format_exc() method to get the type, file and line number of an exception.

main.py
import traceback try: raise ValueError('invalid value') except ValueError as e: print(traceback.format_exc())
The code for this article is available on GitHub

Running the code sample produces the following output.

shell
Traceback (most recent call last): File "/home/borislav/Desktop/bobbyhadz_python/main.py", line 4, in <module> raise ValueError('invalid value') ValueError: invalid value

get type file and line number of exception using format exc

As shown in the output, the name of the file (the absolute path) is shown on the second line.

shell
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.

shell
raise ValueError('invalid value')

The last line shows the type of the error and the message.

shell
ValueError: invalid value

You can achieve the same result by using the traceback.print_exc method.

main.py
import traceback try: raise ValueError('invalid value') except ValueError as e: traceback.print_exc()

Running the code sample produces the following output.

shell
Traceback (most recent call last): File "/home/borislav/Desktop/bobbyhadz_python/main.py", line 4, in <module> raise ValueError('invalid value') ValueError: invalid value

using traceback print exc method instead

# Python: Get the Type, File and Line Number of Exception without any imports

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.

main.py
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}')
The code for this article is available on GitHub

Running the code sample produces the following output.

shell
exception type: ValueError exception filename: /home/borislav/Desktop/bobbyhadz_python/main.py exception line number: 2 exception message: invalid value

get type file and line number of exception without imports

As shown in the code sample, you can access the __name__ attribute to get the exception type directly in the except block.

main.py
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.

main.py
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.

main.py
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.

main.py
try: raise ValueError('invalid value') except ValueError as e: # invalid value e_message = str(e)

# Getting the Type, File and Line Number of multiple exceptions

If you need to get the type, file and line number of multiple (all) exceptions that have occurred, use a while loop.

main.py
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)
The code for this article is available on GitHub

Running the code sample produces the following output.

shell
[{'e_type': 'ValueError', 'e_file': '/home/borislav/Desktop/bobbyhadz_python/main.py', 'e_line': 2, 'e_message': 'invalid value'}]

get type file line number of multiple exceptions

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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.