如何在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 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短