Python Language 捕捉異常


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