捕捉异常
使用 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
- 捕获该类或该异常的任何子类的任何异常。
例如,ZeroDivisionError
是 ArithmeticError
的子类:
>>> ZeroDivisionError.__bases__
(<class 'ArithmeticError'>,)
所以,以下仍将捕捉 ZeroDivisionError
:
try:
5 / 0
except ArithmeticError:
print("Got arithmetic error")