traceback.format_exc() will yield more info if that's what you want.

import traceback

def do_stuff():
    raise Exception("test exception")

try:
    do_stuff()
except Exception:
    print(traceback.format_exc())

This outputs:

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    do_stuff()
  File "main.py", line 5, in do_stuff
    raise Exception("test exception")
Exception: test exception
Answer from volting on Stack Overflow
Top answer
1 of 16
1534

traceback.format_exc() will yield more info if that's what you want.

import traceback

def do_stuff():
    raise Exception("test exception")

try:
    do_stuff()
except Exception:
    print(traceback.format_exc())

This outputs:

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    do_stuff()
  File "main.py", line 5, in do_stuff
    raise Exception("test exception")
Exception: test exception
2 of 16
880

Some other answer have already pointed out the traceback module.

Please notice that with print_exc, in some corner cases, you will not obtain what you would expect. In Python 2.x:

import traceback

try:
    raise TypeError("Oups!")
except Exception, err:
    try:
        raise TypeError("Again !?!")
    except:
        pass

    traceback.print_exc()

...will display the traceback of the last exception:

Traceback (most recent call last):
  File "e.py", line 7, in <module>
    raise TypeError("Again !?!")
TypeError: Again !?!

If you really need to access the original traceback one solution is to cache the exception infos as returned from exc_info in a local variable and display it using print_exception:

import traceback
import sys

try:
    raise TypeError("Oups!")
except Exception, err:
    try:
        exc_info = sys.exc_info()

        # do you usefull stuff here
        # (potentially raising an exception)
        try:
            raise TypeError("Again !?!")
        except:
            pass
        # end of useful stuff


    finally:
        # Display the *original* exception
        traceback.print_exception(*exc_info)
        del exc_info

Producing:

Traceback (most recent call last):
  File "t.py", line 6, in <module>
    raise TypeError("Oups!")
TypeError: Oups!

Few pitfalls with this though:

  • From the doc of sys_info:

    Assigning the traceback return value to a local variable in a function that is handling an exception will cause a circular reference. This will prevent anything referenced by a local variable in the same function or by the traceback from being garbage collected. [...] If you do need the traceback, make sure to delete it after use (best done with a try ... finally statement)

  • but, from the same doc:

    Beginning with Python 2.2, such cycles are automatically reclaimed when garbage collection is enabled and they become unreachable, but it remains more efficient to avoid creating cycles.


On the other hand, by allowing you to access the traceback associated with an exception, Python 3 produce a less surprising result:

import traceback

try:
    raise TypeError("Oups!")
except Exception as err:
    try:
        raise TypeError("Again !?!")
    except:
        pass

    traceback.print_tb(err.__traceback__)

... will display:

  File "e3.py", line 4, in <module>
    raise TypeError("Oups!")
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ traceback.html
traceback โ€” Print or retrieve a stack traceback
Since exceptions can be the roots of large objects graph, this utility can significantly improve memory management. The module uses traceback objects โ€” these are objects of type types.TracebackType, which are assigned to the __traceback__ field of BaseException instances. ... Used to dump Python tracebacks explicitly, on a fault, after a timeout, or on a user signal.
๐ŸŒ
Real Python
realpython.com โ€บ python-traceback
Understanding the Python Traceback โ€“ Real Python
July 29, 2019 - Tracebacks are known by many names, ... Python, the term used is traceback. When your program results in an exception, Python will print the current traceback to help you know what went wrong....
๐ŸŒ
Python Module of the Week
pymotw.com โ€บ 2 โ€บ traceback
traceback โ€“ Extract, format, and print exceptions and stack traces. - Python Module of the Week
import traceback import sys from traceback_example import produce_exception print 'print_exc() with no exception:' traceback.print_exc(file=sys.stdout) print try: produce_exception() except Exception, err: print 'print_exc():' traceback.print_exc(file=sys.stdout) print print 'print_exc(1):' traceback.print_exc(limit=1, file=sys.stdout) In this example, the file handle for sys.stdout is substituted so the informational and traceback messages are mingled correctly: $ python traceback_print_exc.py print_exc() with no exception: None print_exc(): Traceback (most recent call last): File "traceback_
๐ŸŒ
Coursera
coursera.org โ€บ tutorials โ€บ how to print, read, and format a python traceback
How to Print, Read, and Format a Python Traceback | Coursera
March 10, 2023 - A traceback is a Python module you can use to trace an error back to its source. It reports the function calls made at a specific point in your code. When your code throws (or raises) an exception, Python provides a traceback.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ how-to-print-exception-stack-trace-in-python
How to Print Exception Stack Trace in Python - GeeksforGeeks
July 15, 2025 - Traceback (most recent call last): ... a try block, which raises a ZeroDivisionError. The except block catches the exception and prints the detailed error traceback using traceback.print_exc(), helping in debugging by displaying ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ traceback-in-python
Traceback in Python - GeeksforGeeks
August 1, 2020 - # importing module import traceback # declaring array A = [1, 2, 3, 4] try: value = A[5] except: # printing stack trace traceback.print_exc() # out of try-except # this statement is to show that the program continues # normally after the exception is handled print("end of program") Output : Traceback (most recent call last): File "C:/Python27/van.py", line 8, in value = A[5] IndexError: list index out of range end of program >>>
๐ŸŒ
One Two Bytes
onetwobytes.com โ€บ 2021 โ€บ 11 โ€บ 12 โ€บ print-stack-trace-python-exception
Printing Stack Traces in Python Exceptions: A Comprehensive Guide | One Two Bytes
February 6, 2024 - Encountering errors in Python is inevitable. But with stack traces, you can pinpoint the exact location of an exception and diagnose issues effectively. Hereโ€™s a step-by-step guide: ... try: processEvent() # Call the function that might raise an exception except Exception as e: print("Error encountered:", e) traceback.print_exc() # Print the detailed stack trace
Find elsewhere
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ reading-tracebacks-in-python
Deciphering Python's Traceback (most recent call last) - Python Morsels
January 3, 2022 - When exceptions go unhandled, Python prints a traceback. Tracebacks are read from the bottom upward. The last line describes what happened and lines above describe where it happened.
๐ŸŒ
FavTutor
favtutor.com โ€บ blogs โ€บ python-traceback
Python Traceback: How to Read? & Error Types? (with Example)
April 12, 2023 - A Python traceback is used to handle an exception or trace an error that occurred in the line of code. When a Python program has a mistake, the interpreter can create a traceback that provides a series of function calls that went wrong and led ...
๐ŸŒ
Real Python
realpython.com โ€บ ref โ€บ stdlib โ€บ traceback
traceback | Python Standard Library โ€“ Real Python
The Python traceback module provides utilities for working with error tracebacks in Python programs. Itโ€™s particularly useful for debugging and error handling, as it allows you to capture and display the call stack of a program when an exception ...
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_module_traceback.asp
Python traceback Module
The traceback module extracts, formats, and prints stack traces of Python exceptions.
๐ŸŒ
Martin Heinz
martinheinz.dev โ€บ blog โ€บ 66
Creating Beautiful Tracebacks with Python's Exception Hooks | Martin Heinz | Personal Website & Blog
February 1, 2022 - The installation is super easy, all you need to do is install the library, import it and run install function which puts exception hook in place. If you want to just check out a sample output without writing Python code, then you can also use python -m rich.traceback.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ builtins โ€บ exceptions.html
Built-in Exceptions โ€” Python 3.14.7 documentation
Once raised, the current frame is pushed onto the traceback of the OtherException, as would have happened to the traceback of the original SomeException had we allowed it to propagate to the caller. try: ... except SomeException: tb = sys.exception().__traceback__ raise OtherException(...).with_traceback(tb)
๐ŸŒ
DEV Community
dev.to โ€บ martinheinz โ€บ creating-beautiful-tracebacks-with-pythons-exceptions-hooks-4869
Creating Beautiful Tracebacks with Python's Exception Hooks - DEV Community
February 2, 2022 - The installation is super easy, all you need to do is install the library, import it and run install function which puts exception hook in place. If you want to just check out a sample output without writing Python code, then you can also use python -m rich.traceback.
Top answer
1 of 7
137

The answer to this question depends on the version of Python you're using.

In Python 3

It's simple: exceptions come equipped with a __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)

These features are minimally described as part of the raise documentation.

All credit for this part of the answer should go to Vyctor, who first posted this information. I'm including it here only because this answer is stuck at the top, and Python 3 is becoming more common.

In Python 2

It's annoyingly complex. The trouble with tracebacks is that they have references to stack frames, and stack frames have references to the tracebacks that have references to stack frames that have references to... you get the idea. This causes problems for the garbage collector. (Thanks to ecatmur for first pointing this out.)

The nice way of solving this would be to surgically break the cycle after leaving the except clause, which is what Python 3 does. The Python 2 solution is much uglier: you are provided with an ad-hoc function,sys.exc_info(), which only works inside the except clause. It returns a tuple containing the exception, the exception type, and the traceback for whatever exception is currently being handled.

So if you are inside the except clause, you can use the output of sys.exc_info() along with the traceback module to do various useful things:

>>> import sys, traceback
>>> def raise_exception():
...     try:
...         raise Exception
...     except Exception:
...         ex_type, ex, tb = sys.exc_info()
...         traceback.print_tb(tb)
...     finally:
...         del tb
... 
>>> raise_exception()
  File "<stdin>", line 3, in raise_exception

But as your edit indicates, you're trying to get the traceback that would have been printed if your exception had not been handled, after it has already been handled. That's a much harder question. Unfortunately, sys.exc_info returns (None, None, None) when no exception is being handled. Other related sys attributes don't help either. sys.exc_traceback is deprecated and undefined when no exception is being handled; sys.last_traceback seems perfect, but it appears only to be defined during interactive sessions.

If you can control how the exception is raised, you might be able to use inspect and a custom exception to store some of the information. But I'm not entirely sure how that would work.

To tell the truth, catching and returning an exception is kind of an unusual thing to do. This might be a sign that you need to refactor anyway.

2 of 7
116

Since Python 3.0[PEP 3109] the built in class Exception has a __traceback__ attribute which contains a traceback object (with Python 3.2.3):

>>> try:
...     raise Exception()
... except Exception as e:
...     tb = e.__traceback__
...
>>> tb
<traceback object at 0x00000000022A9208>

The problem is that after Googling __traceback__ for a while I found only few articles but none of them describes whether or why you should (not) use __traceback__.

However, the Python 3 documentation for raise says that:

A traceback object is normally created automatically when an exception is raised and attached to it as the __traceback__ attribute, which is writable.

So I assume it's meant to be used.

๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ python โ€บ print stack traces in python
Print stack traces in Python | Sentry
July 3, 2026 - We can use traceback.print_exception to print the traceback of an exception object we pass to it, along with the usual exception information. Since Python 3.10, this function accepts a single exception object as its argument:
๐ŸŒ
Python Module of the Week
pymotw.com โ€บ 3 โ€บ traceback โ€บ index.html
traceback โ€” Exceptions and Stack Traces
The traceback module works with the call stack to produce error messages. A traceback is a stack trace from the point of an exception handler down the call chain to the point where the exception was raised.
๐ŸŒ
Codemia
codemia.io โ€บ home โ€บ knowledge hub โ€บ catch and print full python exception traceback without halting/exiting the program
Catch and print full Python exception traceback without halting/exiting the program | Codemia
December 28, 2024 - To handle exceptions in Python, the try...except block is commonly used. This approach lets you define a block of code to monitor for errors, and a way to react if an error occurs. ... 1try: 2 # Risky code 3 result = 10 / 0 4except ZeroDivisionError as e: 5 print("Caught a ZeroDivisionError:", e) While catching exceptions prevents your program from crashing, it's also vital to log full tracebacks when exceptions occur, particularly to aid in debugging.