Catching Exceptions

suggest change

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

try:
    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  
finally:
    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:

try:
    5 / 0
except ArithmeticError:
    print("Got arithmetic error")

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents