How do I print an exception in Python?
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.
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.
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!
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:
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:
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:
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:
Gotta catch 'em all! (But please, use with caution. You don't want to catch a virus, do you?)
Was this article helpful?