try:
something here
except:
print 'the whatever error occurred.'
How can I print the error/exception in my except:
block?
try:
something here
except:
print 'the whatever error occurred.'
How can I print the error/exception in my except:
block?
In Python 2.6 or greater it's a bit cleaner:
In older versions it's still quite readable:
For Python 2.6 and later and Python 3.x:
For Python 2.5 and earlier, use:
The
traceback
module provides methods for formatting and printing exceptions and their tracebacks, e.g. this would print exception like the default handler does:Output:
In case you want to pass error strings, here is an example from Errors and Exceptions (Python 2.6)
(I was going to leave this as a comment on @jldupont's answer, but I don't have enough reputation.)
I've seen answers like @jldupont's answer in other places as well. FWIW, I think it's important to note that this:
will print the error output to
sys.stdout
by default. A more appropriate approach to error handling in general would be:(Note that you have to
import sys
for this to work.) This way, the error is printed toSTDERR
instead ofSTDOUT
, which allows for the proper output parsing/redirection/etc. I understand that the question was strictly about 'printing an error', but it seems important to point out the best practice here rather than leave out this detail that could lead to non-standard code for anyone who doesn't eventually learn better.I haven't used the
traceback
module as in Cat Plus Plus's answer, and maybe that's the best way, but I thought I'd throw this out there.One liner error raising can be done with assert statements if that's what you want to do. This will help you write statically fixable code and check errors early.