Skip to content

Python get traceback from exception

  • by

Use traceback.format_exc() method to get traceback from exceptions in Python. the traceback Python library that provides a standard interface to extract, format, and print stack traces of Python programs (including those associated with an exception object – e.__traceback__).


It returns a string containing:

  • A header that says Traceback (most recent call last):
  • Stack traceback
  • The exception type and value after the stack trace (eg: NameError: name 'some_var' is not defined)

Python gets traceback from exception

A simple example code gets the traceback:

import traceback

def func1():
raise ValueError("Some error occurred!")

def func2():
return func1()

def func3():
except Exception as e:
# Return the traceback/stack trace as a string
return traceback.format_exc()



Python get traceback from exception

You can use traceback.print_exc() to write to a file instead of returning a string:

except Exception as e:
        with open('print.txt', 'w+') as f:

Extract traceback info from an exception object

It’s simple: exceptions come equipped with an __traceback__ attribute that contains the traceback. This attribute is also writable and can be conveniently set using the with_traceback method of exceptions:

raise Exception("foo occurred").with_traceback(tracebackobj)

Do comment if you have any doubts or suggestions on this Python exception-handling topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *