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