Python exceptions

From wikinotes

Basics

try/except/finally

You can get a list of all of the builtin predefined exceptions here: https://docs.python.org/2/library/exceptions.html You can also define your own custom exceptions, so that they are more meaningful.

try:
    # run code

except IOError:
    # if there was an ioerror, do this. no exception raised

except Exception:
    # if *any* exception was raised, do this

finally:
    # on exception, or successful complete. (Before exception is raised)
    # run this code.

raising Exceptions

When an exception is raised, unless it is caught in a try/except clause, the program halts, and a stacktrace is printed along with the error.

raise IOError('could not find file at {}'.format(filepath))

Custom Exceptions

class MyException( Exception ):										## Define Exception
   pass


Wrapping Exceptions

Occasionally you want to access information about the exception you are currently in.

import sys
import six

try:
    raise RuntimeError()
except(RuntimeError):
    # before exception
    raise  # reraise exception being handled

Or if you only have the last exception's tuple

try:
    raise RuntimeError()
except(Exception):
    (exc_type, exc_value, exc_traceback) = sys.exc_info()
    six.reraise(exc_type, exc_value, exc_traceback)