Report type / name of undefined error in `try` task? python 2
Here is a short example of what I mean -
try:
something_bad
# This works -
except IndexError as I:
write_to_debug_file('there was an %s' % I)
# How do I do this? -
except as O:
write_to_debug_file('there was an %s' % O)
What is the correct syntax for the second exception?
Thank you in advance:)
source to share
except Exception as exc:
Exception
is the base class for all "built-in system-independent exceptions" and should also be the base class for custom ones. except Exception
Hence catch all except those that are not subclasses Exception
such as SystemExit
, GeneratorExit
, KeyboardInterrupt
.
source to share
You don't need to specify the type of error. Just use sys.exc_info()
to read the last exception:
import sys
try:
foobar
except:
print "Unexpected error of type", sys.exc_info()[0].__name__
print "Error message:", sys.exc_info()[1]
Link: https://docs.python.org/2/tutorial/errors.html#handling-exceptions
source to share