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
- Let Python print the default traceback on uncaught exceptions.
- Use
traceback.format_exc()inside anexceptblock to capture it as a string. - 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
richandbetter-exceptionsprovide colored, enhanced tracebacks. - In web frameworks, custom error handlers use
tracebackto 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
raiseinsideexceptpreserves the original traceback;raise ecreates a new one.