Python Language Catching Exceptions


Use try...except: to catch exceptions. You should specify as precise an exception as you can:

    x = 5 / 0
except ZeroDivisionError as e:
    # `e` is the exception object
    print("Got a divide by zero! The exception was:", e)
    # handle exceptional case
    x = 0  
    print "The END"
    # it runs no matter what execute.

The exception class that is specified - in this case, ZeroDivisionError - catches any exception that is of that class or of any subclass of that exception.

For example, ZeroDivisionError is a subclass of ArithmeticError:

>>> ZeroDivisionError.__bases__
(<class 'ArithmeticError'>,)

And so, the following will still catch the ZeroDivisionError:

    5 / 0
except ArithmeticError:
    print("Got arithmetic error")
Catching multiple exceptions