traceback

Updated March 13, 2026 · Modules
exception debugging traceback stdlib

The traceback module provides tools for extracting, formatting, and printing Python stack traces. It is part of the standard library and works with any exception or traceback object. This module is essential for logging errors, building custom error handlers, and debugging applications in production.

Syntax

import traceback

Functions

traceback.print_exc()

Prints the current exception traceback to sys.stderr.

try:
    1 / 0
except ZeroDivisionError:
    traceback.print_exc()
# Traceback (most recent call last):
#   File "<stdin>", line 2, in <module>
# ZeroDivisionError: division by zero

traceback.format_exc()

Returns the current exception traceback as a formatted string instead of printing it.

try:
    result = {}
    value = result["missing_key"]
except KeyError:
    error_text = traceback.format_exc()
    print("Caught error:", error_text)

traceback.print_exception()

Prints exceptions to a file. It accepts more parameters than print_exc().

import sys

try:
    int("not_a_number")
except ValueError:
    traceback.print_exception(
        exc_type=ValueError,
        exc_value=ValueError("invalid literal for int()"),
        exc_tb=sys.exc_info()[2],
        file=sys.stderr
    )

traceback.format_exception()

Formats an exception as a list of strings. Use this when you need full control over the output format.

import sys

try:
    [][0]
except IndexError as e:
    formatted = traceback.format_exception(type(e), e, e.__traceback__)
    for line in formatted:
        print(line, end="")

traceback.extract_tb()

Extracts traceback information from a traceback object as a list of FrameSummary objects.

import traceback
import sys

def faulty_function():
    return 1 + "2"  # TypeError

try:
    faulty_function()
except TypeError:
    tb = sys.exc_info()[2]
    extracted = traceback.extract_tb(tb)
    for frame in extracted:
        print(f"File: {frame.filename}, Line: {frame.lineno}, in {frame.name}")

traceback.extract_stack()

Extracts the current call stack as a list of FrameSummary objects.

import traceback

def level_three():
    return traceback.extract_stack()

def level_two():
    return level_three()

def level_one():
    return level_two()

stack = level_one()
for frame in stack:
    print(f"{frame.filename}:{frame.lineno} in {frame.name}")

Parameters for print_exception() and format_exception()

ParameterTypeDefaultDescription
exc_typetypeThe exception class
exc_valueBaseExceptionThe exception instance
exc_tbtracebackThe traceback object
limitintNoneNumber of stack entries to print
filefile-likesys.stderrWhere to write output

Common Patterns

Custom error logging

import logging
import traceback
import sys

logging.basicConfig(level=logging.ERROR)

def log_exception():
    logging.error("An error occurred:\n%s", traceback.format_exc())

try:
    open("nonexistent.txt")
except FileNotFoundError:
    log_exception()

Pretty-printing exceptions in CLI tools

import traceback
import sys

def main():
    try:
        # Your application code
        pass
    except Exception:
        print("Error! Traceback:", file=sys.stderr)
        traceback.print_exc()
        sys.exit(1)

Errors

  • traceback.print_exc() requires an active exception context. It raises TypeError if called outside an except block.
  • The limit parameter limits the number of stack frames shown, counting from the innermost frame outward.

See Also