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
February 22, 2026 - Format the exception part of a traceback using an exception value such as given by sys.last_value. The return value is a list of strings, each ending in a newline. The list contains the exception’s message, which is normally a single string; however, for SyntaxError exceptions, it contains several lines that (when printed) display detailed information about where the syntax error occurred. Following the message, the list contains the exception’s notes. Since Python 3.10, instead of passing value, an exception object can be passed as the first argument.
🌐
Real Python
realpython.com › python-traceback
Understanding the Python Traceback – Real Python
July 31, 2023 - In this step-by-step tutorial, you'll learn how to read and understand the information you can get from a Python traceback. You'll walk through several examples of tracebacks and see some of the most common tracebacks in Python.
🌐
Coursera
coursera.org › tutorials › python-traceback
How to Print, Read, and Format a Python Traceback | Coursera
Here’s an example of a Python traceback in response to an AttributeError: Starting from the bottom, we can see that we've generated an AttributeError in line 2 of our code. This was caused by trying to use the attribute append on the variable drinks, which we defines as a string. Since string objects have no attribute append, the interpreter raised an error. ... Learn more about exception types in the previous tutorial: How to Catch, Raise and Print a Python Exception.
🌐
Real Python
realpython.com › ref › stdlib › traceback
traceback | Python Standard Library – Real Python
>>> import traceback >>> try: ... # Open a non-existing file ... with open("file.txt", mode="r", encoding="utf-8") as file: ... content = file.read() ... except FileNotFoundError as e: ... with open("error.log", "w") as log_file: ... log_file.write(traceback.format_exc()) ... By writing the stack trace to error.log, you ensure that detailed error information is available for future review—making debugging and troubleshooting much easier. This technique provides a reliable way to capture detailed error information for later debugging and troubleshooting. ... In this step-by-step tutorial, you'll learn how to read and understand the information you can get from a Python traceback.
🌐
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.
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!")
🌐
Python
docs.python.org › 3.10 › library › traceback.html
traceback — Print or retrieve a stack traceback — Python 3.10.19 documentation
Format the exception part of a traceback using an exception value such as given by sys.last_value. The return value is a list of strings, each ending in a newline. Normally, the list contains a single string; however, for SyntaxError exceptions, it contains several lines that (when printed) display detailed information about where the syntax error occurred.
🌐
MachineLearningMastery
machinelearningmastery.com › home › blog › understanding traceback in python
Understanding Traceback in Python - MachineLearningMastery.com
June 21, 2022 - When an exception occurs in a Python program, often a traceback will be printed. Knowing how to read the traceback can help you easily identify the error and make a fix. In this tutorial, we are going to see what the traceback can tell you. After completing this tutorial, you will know: How to read a traceback How to print…
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python-traceback
Python Traceback - GeeksforGeeks
July 23, 2020 - Going through a few tracebacks ... section we will see how to read a particular exception. In python it is best to read traceback from bottom to top....
🌐
Python Module of the Week
pymotw.com › 2 › traceback
traceback – Extract, format, and print exceptions and stack traces. - Python Module of the Week
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_print_exc.py", line 20, in <module> produce_exception() File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 16, in produce_exception produce_exception(recursion_level-1) File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 16, in produce_exception produce_exception
🌐
W3Schools
w3schools.com › python › ref_module_traceback.asp
Python traceback Module
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... import traceback try: result = 10 / 0 except ZeroDivisionError: tb = traceback.format_exc() print('Exception caught and formatted') Try it Yourself »
🌐
EDUCBA
educba.com › home › software development › software development tutorials › python tutorial › traceback in python
Traceback in Python | How Traceback Works? | Examples
April 11, 2023 - Guide to Traceback in Python. Here we discuss the definition, syntax, Working of Traceback along with Examples, and code implementation.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
FavTutor
favtutor.com › blogs › python-traceback
Python Traceback: How to Read? & Error Types? (with Example)
April 12, 2023 - Understand what is Traceback in Python and How to read and import it with an example. Also, what are the uses of tracebacks in a program?
🌐
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 ...
🌐
Acid & Base
sceweb.sce.uhcl.edu › helm › WEBPAGE-Python › documentation › python_tutorial › lib › module-traceback.html
3.6 traceback -- Print or retrieve a stack traceback.
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) Next: 3.7 pickle Up: 3. Python Services Previous: 3.5 operator
🌐
The Engineering Projects
theengineeringprojects.com › home › blog › python › python traceback
Python Traceback - The Engineering Projects
March 16, 2022 - In today's tutorial, we will discuss what is Python Trackback? How to use Tracebacks in Python? We will cover all the related details.
🌐
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 - Python provides a module named traceback which has a list of method which let us extract error traces, format it and print it according to our need. This can help with formatting and limiting error trace getting generated.
🌐
O'Reilly
oreilly.com › library › view › python-standard-library › 0596000960 › ch02s11.html
The traceback Module - Python Standard Library [Book]
May 10, 2001 - The traceback module in Example 2-18 allows you to print exception tracebacks inside your programs, just like the interpreter does when you don’t catch an exception yourself.
Author   Fredrik Lundh
Published   2001
Pages   304
🌐
Fmyly
en.fmyly.com › article › how-do-you-print-a-traceback-in-python
How Do You Print a Traceback in Python: A Comprehensive Guide for Debugging Success - Fmyly
13 hours ago - Essentially, a Python traceback is an invaluable report generated by the Python interpreter when an unhandled exception occurs. It’s a step-by-step account of the function calls that led to the error, starting from the initial invocation and going all the way down to the precise line of code where the problem surfaced.