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.
ZeroDivisionError is a subclass of
>>> ZeroDivisionError.__bases__ (<class 'ArithmeticError'>,)
And so, the following will still catch the
try: 5 / 0 except ArithmeticError: print("Got arithmetic error")