如何在Python中的一个except块中引发异常并在更高的except块中捕获它?
在try块中仅调用一个except子句。如果您希望将异常捕获到更高的位置,则需要使用嵌套的try块。
让我们写2个try...except这样的块:
try:
try:
1/0
except ArithmeticError as e:
if str(e) == "Zero division":
print ("thumbs up")
else:
raise
except Exception as err:
print ("thumbs down")
raise err我们得到以下输出
thumbs down Traceback (most recent call last): File "C:/Users/nhooo1/~.py", line 11, in <module> raise err File "C:/Users/nhooo1/~.py", line 3, in <module> 1/0 ZeroDivisionError: division by zero
根据python教程,每条try语句只有一个捕获或捕获的异常。
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志