Catch and print full Python exception traceback without halting/exiting the program
Capture any exception's traceback using traceback.print_exc()
, letting your program go on:
Use traceback.print_exc()
within except Exception:
to both capture the full traceback and let your program carry on doing its thing.
Handling errors without blocking the party
To seize the traceback for late-night error analysis, use traceback.format_exc()
. It provides a full exception traceback as a string:
For a more tuned approach when dealing with exceptions, sys.exc_info()
provides a tuple containing exception type, value, and traceback detail. Exceptionally useful for custom handling of trivial to catastrophic exceptions.
Advanced exception handling
Use logging
for hardcore error tracking
Instead of letting the exceptions scream in the console, make them whisper silently into your logs using logging
with logger.exception()
. It will broadcast your secrets, but includes the traceback too:
Tidy up with sys.exc_info()
Clear sys.exc_info()
references after every rollout to avoid circular references. Even with automatic garbage collection in Python 2.2 and later, it's good practice to maximize your tidiness score:
Get the traceback
of your execution journey
To log the state of stack without exceptions use traceback.print_stack()
. It's like taking a selfie of your code at its current state:
Mastering the art of tracebacks
Python 3's secret weapon err.__traceback__
Python 3 unleashes __traceback__
to easily grab the traceback bound to an exception object:
Speaking your logger's language
Use logger level and format to dictate verbosity and mannerism:
Choosing your traceback gear
Select between traceback.print_exc()
, logger.exception()
, or traceback.format_exc()
. It's like choosing between print, log, or store - Variety is spice of life, after all!
Was this article helpful?