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
🌐
AskPython
askpython.com › home › understanding tracebacks in python
Understanding Tracebacks in Python - AskPython
February 16, 2023 - Traceback is the message or information or a general report along with some data, provided by Python that helps us know about an error that has occurred in
🌐
Python
docs.python.org › 3 › library › traceback.html
traceback — Print or retrieve a stack traceback
February 22, 2026 - 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...
🌐
Python
docs.python.org › es › 3.7 › library › traceback.html
traceback — Print or retrieve a stack traceback — documentación de Python - 3.7.17
June 28, 2023 - This simple example implements a basic read-eval-print loop, similar to (but less useful than) the standard Python interactive interpreter loop. For a more complete implementation of the interpreter loop, refer to the code module. import sys, traceback def run_user_code(envdir): source = input(">>> ") try: exec(source, envdir) except Exception: print("Exception in user code:") print("-"*60) traceback.print_exc(file=sys.stdout) print("-"*60) envdir = {} while True: run_user_code(envdir)
Top answer
1 of 16
1525

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
879

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 › how-to-print-exception-stack-trace-in-python
How to Print Exception Stack Trace in Python - GeeksforGeeks
July 15, 2025 - In Python, when an exception occurs, a stack trace provides details about the error, including the function call sequence, exact line and exception type. This helps in debugging and identifying issues quickly. ... Let's explore different methods to achieve this. traceback.print_exc() is a simple way to print the full exception stack trace directly to the console.
🌐
W3Schools
w3schools.com › python › ref_module_traceback.asp
Python traceback Module
The traceback module extracts, formats, and prints stack traces of Python exceptions.
Find elsewhere
🌐
Developpez
python.developpez.com › cours › docs.python.org › 2.6 › library › traceback.php
Print or retrieve a stack traceback - Python
This simple example implements a basic read-eval-print loop, similar to (but less useful than) the standard Python interactive interpreter loop. For a more complete implementation of the interpreter loop, refer to the code module. import sys, traceback def run_user_code(envdir): source = raw_input(">>> ") try: exec source in envdir except: print "Exception in user code:" print '-'*60 traceback.print_exc(file=sys.stdout) print '-'*60 envdir = {} while 1: run_user_code(envdir)
🌐
Cybrosys Technologies
cybrosys.com › odoo blogs
What is Traceback Module in Python?
Traceback is mainly used to print stack traces of a python program. This package provides a standard interface for the user to format and extract as they see fit.
🌐
CircuitPython
docs.circuitpython.org › en › latest › shared-bindings › traceback
traceback – Traceback Module — Adafruit CircuitPython 1 documentation
If the exception value is passed in value, then any value passed in for exc is ignored. value is used as the exception value and the traceback in the tb argument is used. In this case, if tb is None, no traceback will be shown.
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.rename.html
pandas.DataFrame.rename — pandas 3.0.1 documentation
>>> df.rename(columns={"A": "a", "B": "b", "C": "c"}, errors="raise") Traceback (most recent call last): KeyError: ['C'] not found in axis
🌐
Jython
jython.org › jython-old-sites › docs › library › traceback.html
26.7. traceback — Print or retrieve a stack traceback — Jython v2.5.2 documentation
It exactly mimics the behavior of the Python interpreter when it prints a stack trace. This is useful when you want to print stack traces under program control, such as in a “wrapper” around the interpreter. The module uses traceback objects — this is the object type that is stored in the variables sys.exc_traceback (deprecated) and sys.last_traceback and returned as the third item from sys.exc_info().
🌐
Real Python
realpython.com › python-traceback
Understanding the Python Traceback – Real Python
July 31, 2023 - Python prints a traceback when an exception is raised in your code. The traceback output can be a bit overwhelming if you’re seeing it for the first time or you don’t know what it’s telling you.
🌐
Bite Code
bitecode.dev › p › why-and-how-to-hide-the-python-stack
Why and how to hide the Python stack trace - Bite code!
June 3, 2023 - import sys SHOW_STACK_TRACE = False def on_crash(exctype, value, traceback): # "exctype" is the class of the exception raised # "value" is the instance # "traceback" is the object containing the what python needs to print the # stack trace if SHOW_STACK_TRACE: # sys.__excepthook__ is the default excepthook that prints the stack trace # so we use it directly if we want to see it sys.__excepthook__(exctype, value, traceback) else: # Instead of the stack trace, we print an error message to stderr print('Something went wrong, you can contact us at <email>', file=sys.stderr) print('Or go to <website> for more help', file=sys.stderr) # Now we replace the default excepthook by our own sys.excepthook = on_crash
🌐
Real Python
realpython.com › ref › glossary › traceback
traceback | Python Glossary – Real Python
A traceback is the structured sequence of function calls that the Python interpreter prints whenever an exception (error) is raised.
🌐
Python
docs.python.org › 3 › library › faulthandler.html
faulthandler — Dump the Python traceback
Dump the tracebacks of all threads into file. If all_threads is False, dump only the current thread. ... Changed in version 3.5: Added support for passing file descriptor to this function. Added in version 3.14. ... Dump the C stack trace of the current thread into file. If the Python build does not support it or the operating system does not provide a stack trace, then this prints an error in place of a dumped C stack.
🌐
Medium
iamdamilare13.medium.com › exploring-python-tracebacks-types-and-functions-c7c5973abaea
Exploring Python Tracebacks: Types and Functions | by Damilare Daramola | Medium
December 11, 2024 - A traceback is essentially a detailed report generated by Python when your code encounters an exception. It shows the sequence of function calls leading to the error, pinpointing exactly where in your code things went wrong.
🌐
Python.org
discuss.python.org › ideas
InputError: Show an error message without a traceback - Ideas - Discussions on Python.org
April 16, 2019 - When writing command line applications, I often end up defining some classes of ‘input error’, which relate to bad input - from command line arguments, config files, etc. The traceback to the code that raised them isn’t important, so the top level of my code does something like this to hide tracebacks for those errors: try: main() except InputError as e: sys.exit(str(e)) # Print the message to stderr and exit with status 1 This is analogous to the difference between HTTP 5xx errors (s...
🌐
Python.org
discuss.python.org › python help
How to get a full stack summary from a traceback.TracebackException - Python Help - Discussions on Python.org
January 29, 2024 - Hi, The docs say that a TracebackException’s stack attribute is a stack summary but it seems to be only a frame. How can I get the stack from the tbe? I would like to save a TracebackException object in one process and log a stack trace later in another. The snippet below prints tbe.stack=[ ] Similarly, traceback.TracebackException.from_exception(e).format() does not include function a; however traceback.format_stack() has both a an...
🌐
GeeksforGeeks
geeksforgeeks.org › python › traceback-in-python
Traceback in Python - GeeksforGeeks
August 1, 2020 - Traceback is a python module that provides a standard interface to extract, format and print stack traces of a python program. When it prints the stack trace it exactly mimics the behaviour of a python interpreter.