Explain Codes LogoExplain Codes Logo

How do I print an exception in Python?

python
exception-handling
logging
debugging
Alex KataevbyAlex Kataev·Oct 2, 2024
TLDR

To capture and display an error in Python, grab your net and bucket, I mean, use the except block, assign the error to a variable using the as keyword, then simply print that variable.

try: # Insert all risky business here except Exception as e: print(f"Error: {e}") # Error: captured!

This properly formatted error message might just lead you straight to your coding eureka moment.

The overachievers' way: traceback

Had more complicated errors before and have a hangover, I mean, a traceback? traceback.print_exc() is the aspirin of Python functions, providing a much-needed context of that menacing error.

import traceback try: # Daredevil code here except Exception as e: traceback.print_exc() # Never mind solving. I mean, "dissolving". Just print it.

This prints the stack trace, so you can finally see what's been wreaking havoc behind the scenes.

Pro tip: logging exceptions

Why print when you can LOG (perhaps to complain later to a friend)? Utilize Python's logging module for your gripes... I mean, exceptions, of course!

import logging try: # some risky operation except Exception as e: logging.exception("Error just chilling here:")

logging.exception() gives a detailed account of the culprit traceback. Next time, errors won't just sneak past your code.

Exception alert: sys.stderr

Errors can be sneaky. Let's get them in the spotlight by directing them to sys.stderr, like an MC announcing a not-so-popular guest:

import sys try: # a bit of specious code except Exception as e: print(f"Alert! Found an error: {e}", file=sys.stderr) # The spotlight's on you, Error!

Using sys.stderr makes sure your errors don’t duck into the anonymity of your standard output.

Turn the dial up: advanced debugging

Full error profile with sys.exc_info()

Hair pulling over not having enough error info? Have some more! sys.exc_info() hands you the type, value, and a backtrace of the exception:

import sys try: # a failing piece of code except: exc_type, exc_value, exc_traceback = sys.exc_info() print(f"Exception type: {exc_type.__name__}, Value: {exc_value}", file=sys.stderr)

It's like your error's resumé. Enough for an interview, wouldn't you agree?

Chain of blunders: exception chaining

Like a perfect storm of errors leading to a catastrophe, Python 3 introduced exception chaining, letting us foresee a storm before it hits:

try: # initial tricky operation except IOError as intermediate_exception: try: # retrying operation except FileNotFoundError as final_exception: raise RuntimeError('Both operations failed') from final_exception

Just like dominos, one error leading to another. How elegant!

World-class bug hunter: catch all exceptions

Think you've seen all kinds of errors? Think again! Here's a way to catch all exceptions, even keyboard interrupts:

try: # code that must keep running except BaseException as e: logging.critical('We caught an alien! I mean...unforeseen exception.', exc_info=True)

Gotta catch 'em all! (But please, use with caution. You don't want to catch a virus, do you?)