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
🌐
Python
docs.python.org › 3 › library › traceback.html
traceback — Print or retrieve a stack traceback
Source code: Lib/traceback.py This module provides a standard interface to extract, format and print stack traces of Python programs. It is more flexible than the interpreter’s default traceback di...
🌐
W3Schools
w3schools.com › python › ref_module_traceback.asp
Python traceback Module
import traceback try: result = 10 / 0 except ZeroDivisionError: tb = traceback.format_exc() print('Exception caught and formatted') Try it Yourself »
🌐
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 occurs. ... >>> import traceback >>> try: ...
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!")
🌐
GeeksforGeeks
geeksforgeeks.org › python › traceback-in-python
Traceback in Python - GeeksforGeeks
August 1, 2020 - format_exception_only() : Formats the exception part of the traceback. It also returns strings ending newlines. Normally, the generator emits a single string; however, for SyntaxError exceptions, it emits several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is always the last string in the output. Example : ... # importing the modules import traceback import sys a=3 b=0 try: a/b except Exception as e: exc_type, exc_value, exc_tb = sys.exc_info() tb = traceback.TracebackException(exc_type, exc_value, exc_tb) print(''.join(tb.format_exception_only())) Output :
🌐
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)
🌐
Sentry
sentry.io › sentry answers › python › print stack traces in python
Print stack traces in Python | Sentry
July 3, 2026 - The function traceback.print_stack will print a stack trace at the current point in our script’s invocation. The optional limit parameter allows us to control how many entries are printed — by default, the entire stack trace will be printed. Consider the following example script: import traceback def trace(): traceback.print_stack() def do_something(): a = 1 + 2 trace() do_something()
Find elsewhere
🌐
Real Python
realpython.com › python-traceback
Understanding the Python Traceback – Real Python
July 29, 2019 - When attempting to import something that doesn’t exist, asdf, from a module that does exists, collections, this results in an ImportError. The error message lines at the bottom of the tracebacks tell you which thing couldn’t be imported, asdf in both cases.
🌐
Coderz Column
coderzcolumn.com › tutorials › python › traceback-how-to-extract-format-and-print-error-stack-traces-in-python
traceback - How to Extract, Format, and Print Error Stack Traces in Python by Sunny Solanki
January 14, 2021 - As a part of this example, we have explained how we can direct the trace generated to a file. We have directed the error trace generated by the code to a file named traceback_ex1.out. import traceback import random try: out = random.randint(-5,-10) except Exception as e: traceback.print_tb(e.__traceback__, file=open("traceback_ex1.out", "w"))
🌐
Python Module of the Week
pymotw.com › 3 › traceback › index.html
traceback — Exceptions and Stack Traces
The examples in this section use the module traceback_example.py. ... import traceback import sys def produce_exception(recursion_level=2): sys.stdout.flush() if recursion_level: produce_exception(recursion_level - 1) else: raise RuntimeError() def call_function(f, recursion_level=2): if recursion_level: return call_function(f, recursion_level - 1) else: return f()
🌐
FavTutor
favtutor.com › blogs › python-traceback
Python Traceback: How to Read? & Error Types? (with Example)
April 12, 2023 - The Python traceback module is an in-built module that offers capabilities and provides functionalities for using Tracebacks. Moreover, once an individual has imported the traceback module, it can be used to manipulate tracebacks, edit or print it too.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-print-exception-stack-trace-in-python
How to Print Exception Stack Trace in Python - GeeksforGeeks
July 15, 2025 - Instead of printing directly, it allows further processing, such as storing errors in logs or sending them in reports. This method provides flexibility while maintaining detailed traceback information. ... import traceback try: 1 / 0 # division by zero except Exception: error_msg = traceback.format_exc() print(error_msg)
🌐
PyPI
pypi.org › project › traceback2
traceback2 · PyPI
A backport of traceback to older supported Pythons. >>> import traceback2 as traceback · Profit. Things to be aware of! In Python 2.x, unlike traceback, traceback2 creates unicode output (because it depends on the linecache2 module).
      » pip install traceback2
    
Published: Mar 09, 2015
Version: 1.4.0
🌐
Jython
jython.org › jython-old-sites › docs › library › traceback.html
26.7. traceback — Print or retrieve a stack traceback — Jython v2.5.2 documentation
This differs from print_tb() in the following ways: (1) if traceback is not None, it prints a header Traceback (most recent call last):; (2) it prints the exception type and value after the stack trace; (3) if type is SyntaxError and value has the appropriate format, it prints the line where ...
🌐
PyPI
pypi.org › project › traceback-with-variables
traceback-with-variables 2.2.1
JavaScript is disabled in your browser. Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
Alexwlchan
alexwlchan.net › notes › 2025 › get-python-traceback-as-string
Get a string representation of a Python traceback with traceback.format_exc() – alexwlchan
June 13, 2025 - import traceback try: 1/0 except Exception: print(repr(traceback.format_exc())) And here’s the output: $ python3 exception.py 'Traceback (most recent call last):\n File "exception.py", line 4, in <module>\n 1/0\n ~^~\nZeroDivisionError: division by zero\n' It’s all the text that would be printed to stderr, but now saved in a handy string I can keep for later.
🌐
O'Reilly
oreilly.com › library › view › python-standard-library › 0596000960 › ch02s11.html
The traceback Module - Python Standard Library [Book]
May 10, 2001 - File: traceback-example-1.py # note! importing the traceback module messes up the # exception state, so you better do that here and not # in the exception handler import traceback try: raise SyntaxError, "example" except: traceback.print_exc() Traceback (innermost last): File "traceback-ex...
Author: Fredrik Lundh
Published: 2001
Pages: 304
🌐
GitHub
github.com › python › cpython › blob › main › Lib › traceback.py
cpython/Lib/traceback.py at main · python/cpython
Did you forget to import '{wrong_name}'?" if lookup_lines: self._load_lines() self.__suppress_context__ = \ exc_value.__suppress_context__ if exc_value is not None else False · · # Convert __cause__ and __context__ to `TracebackExceptions`s, use a ·
Author: python