How do I read and format exception tracebacks in Python?

· Category: Python Programming

Short answer

A traceback shows the sequence of function calls that led to an exception. Python's built-in traceback module allows you to extract, format, and print tracebacks programmatically for logging or custom error pages.

Steps

  1. Let Python print the default traceback on uncaught exceptions.
  2. Use traceback.format_exc() inside an except block to capture it as a string.
  3. Use traceback.print_tb() for custom formatting.
import traceback

def risky():
    return 1 / 0

try:
    risky()
except ZeroDivisionError:
    tb = traceback.format_exc()
    print("Logged error:")
    print(tb)

Tips

  • traceback.format_exception_only() captures just the exception type and message without the stack.
  • sys.exc_info() returns (type, value, traceback) for manual inspection.
  • Third-party libraries like rich and better-exceptions provide colored, enhanced tracebacks.
  • In web frameworks, custom error handlers use traceback to render user-friendly error pages.

Common issues

  • Holding references to traceback objects can create reference cycles and delay garbage collection.
  • Printing tracebacks in production without sanitization can leak sensitive file paths or data.
  • Re-raising an exception with raise inside except preserves the original traceback; raise e creates a new one.