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:)

+3


source to share


3 answers


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

.

+3


source


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

0


source


As Jason already pointed out, you can use except Exception as O

or except BaseException as O

if you want to catch all exceptions, including KeyboardInterrupt

.

If you need the name of the exception, you can use name = O.__class__.__name__

or name = type(O).__name__

.

Hope it helps

0


source







All Articles