Table of Contents

import traceback

import traceback is a Python import that prints and analyzes exception tracebacks. Use it to log detailed error information without stopping the program.

Example

# Python
# description: print and format exception tracebacks
 
import traceback
 
def risky_function():
    data = [1, 2, 3]
    return data[10]  # IndexError
 
try:
    risky_function()
except IndexError:
    # Print full traceback to stderr
    traceback.print_exc()
 
    # Get traceback as string
    error_str = traceback.format_exc()
    print("Logged:", error_str)
 
    # Print just the exception line
    traceback.print_exc(limit=1)
 
# Get current traceback
import sys
if sys.exc_info()[0] is not None:
    traceback.print_exc()

Common functions