Catching Exceptions

Download python eBook

Example

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

Stats

Contributors: 4
2016-11-06
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook