捕捉異常

使用 try...except:來捕獲異常。你應該儘可能精確地指定異常:

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.

指定的異常類 - 在本例中為 ZeroDivisionError - 捕獲該類或該異常的任何子類的任何異常。

例如,ZeroDivisionErrorArithmeticError 的子類:

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

所以,以下仍將捕捉 ZeroDivisionError

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