Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Standard Library: Concurrency, Network and Tools

The traceback module

Reference for Python's traceback module: print_exc, format_exc, format_exception, extract_tb, TracebackException, print_stack and how to log full stack traces.

The traceback module reads, formats and prints the stack information that Python attaches to an exception. It lets you do what the interpreter does when a program crashes (print the familiar "Traceback (most recent call last)" report) while your program keeps running: write it to a log, show it in a window, or send it to a monitoring service.

Most of the time you need only two calls: traceback.print_exc() or traceback.format_exc() inside an except block. The rest of the module is for custom reports, such as picking out the innermost frame.

Python
import traceback

try:
    1 / 0
except ZeroDivisionError:
    text = traceback.format_exc()
    print(text.splitlines()[-1])

Try it

Python Capturing a traceback as text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Inspecting frames and chained errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
traceback.print_exc(limit=None, file=None, chain=True)
traceback.format_exc(limit=None, chain=True)
traceback.print_exception(exc, /, value=..., tb=..., limit=None, file=None, chain=True)
traceback.format_exception(exc, /, ...)
traceback.format_exception_only(exc, /, ...)
traceback.extract_tb(tb, limit=None)
traceback.extract_stack(f=None, limit=None)
traceback.print_stack(f=None, limit=None, file=None)
traceback.TracebackException.from_exception(exc)
Name Description
exc An exception object. Since Python 3.10 you can pass just the exception; older code passes type, value, tb.
limit Show only this many frames (positive: from the outermost end; negative: from the innermost end).
file Where to print; the default is standard error (sys.stderr).
chain Include chained exceptions (__cause__ and __context__). Default True.
tb A traceback object, such as exc.__traceback__.

Return values: print_* functions return None. format_exc() returns one string. format_exception() and format_exception_only() return lists of strings (each ending in a newline). extract_tb() and extract_stack() return a StackSummary, a list of FrameSummary objects with filename, lineno, name and line.

Usage notes

  • print_exc() and format_exc() work only while handling an exception (inside except or finally). Elsewhere they report NoneType: None.
  • Output goes to stderr by default, mixed with other error messages. Pass file=sys.stdout or capture text with format_exc() to redirect it.
  • For logging, logging.exception("msg") or logger.error("msg", exc_info=True) includes the traceback for you.
  • The traceback hangs on the exception: exc.__traceback__ stays available after the except block, but the name exc itself is deleted at the end of that block.
  • Reference cycles: storing a traceback in a variable that the frames can reach (for example a local in the same function) can keep objects alive longer than expected. Delete it or convert it to text.
  • Chained errors print "The above exception was the direct cause of the following exception" (raise ... from ...) or "During handling of the above exception, another exception occurred" (implicit context).
  • TracebackException is the modern object behind all of this; .format() yields lines, and Python 3.11+ also records __notes__ from add_note().
  • Don't show tracebacks to end users of a website or app. Log them and show a friendly message.
  • Source lines (frame.line) come from files on disk. They are empty for code from exec() or the interactive prompt.
  • Colors: since Python 3.13 the interpreter colors its own tracebacks in a terminal; strings from format_exc() have no color codes unless asked for.