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...
🌐
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
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!")
🌐
Real Python
realpython.com › python-traceback
Understanding the Python Traceback – Real Python
July 29, 2019 - A traceback is a report containing the function calls made in your code at a specific point. Tracebacks are known by many names, including stack trace, stack traceback, backtrace, and maybe others. In Python, the term used is traceback.
🌐
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.
🌐
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.
🌐
Python Module of the Week
pymotw.com › 2 › traceback
traceback – Extract, format, and print exceptions and stack traces. - Python Module of the Week
Now available for Python 3! Buy the book! ... 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.
🌐
Python
docs.python.org › 3.8 › library › traceback.html
traceback — Print or retrieve a stack traceback — Python 3.8.20 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 sys.last_traceback variable and returned as the third item from sys.exc_info().
Find elsewhere
🌐
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.
🌐
W3Schools
w3schools.com › python › ref_module_traceback.asp
Python traceback Module
The traceback module extracts, formats, and prints stack traces of Python exceptions.
🌐
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 ...
🌐
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.
🌐
MachineLearningMastery
machinelearningmastery.com › home › blog › understanding traceback in python
Understanding Traceback in Python - MachineLearningMastery.com
June 21, 2022 - If you run this program using the Python interpreter, you will see this: The lines starting with “Traceback (most recent call last):” are the traceback. It is the stack of your program at the time when your program encountered the exception. In ...
🌐
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.
🌐
University of New Brunswick
cs.unb.ca › ~bremner › teaching › cs2613 › books › python3-doc › library › traceback.html
traceback — Print or retrieve a stack traceback — Python 3.9.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 sys.last_traceback variable and returned as the third item from sys.exc_info().
🌐
AskPython
askpython.com › python › examples › 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 our program. It’s also called raising an exception in technical terms.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-traceback
Python Traceback - GeeksforGeeks
July 23, 2020 - Traceback (most recent call last): File "gfg.py", line 5, in print(mylist[10]) IndexError: list index out of range · KeyError: Similar to the IndexError, the KeyError is raised when you attempt to access a key that isn’t in the mapping, usually in the case of Python dict.
🌐
Medium
medium.com › data-science › python-tracebacks-explained-538caaac434
Python Tracebacks — Explained. A great helper for debugging. | by Soner Yıldırım | TDS Archive | Medium
December 13, 2022 - A traceback in Python can be considered as a report that helps us understand and fix a problem in the code.