Explain Codes LogoExplain Codes Logo

Catch and print full Python exception traceback without halting/exiting the program

python
exception-handling
logging
traceback
Nikita BarsukovbyNikita Barsukov·Oct 5, 2024
TLDR

Capture any exception's traceback using traceback.print_exc(), letting your program go on:

import traceback try: # Code that could launch a space shuttle or just crash and burn risky_operation() except Exception: traceback.print_exc() # Catching an error, one traceback at a time # The fun continues here

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:

import traceback try: oh_no_an_error() except Exception as e: error_traceback = traceback.format_exc() # Save for late-night reading or pass it forward

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:

import logging log = logging.getLogger(__name__) try: code_that_might_explode() except Exception as error: log.exception('Boom! Error Occurred') # Logging controversies along with traceback

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:

try: # code that could probably stir up a storm except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info() # Handle your storms here finally: del exc_traceback # Clean up after the party

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:

import traceback def function_in_the_wild(): # Curious about who got you here? traceback.print_stack() function_in_the_wild()

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:

try: raise ValueError('Custom error message') except Exception as err: tb = err.__traceback__ print(tb)

Speaking your logger's language

Use logger level and format to dictate verbosity and mannerism:

logging.basicConfig( level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s' ) # Now, every log speaks in a nicer, more informative tone

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!