2020年4月7日 / 22,920次阅读 / Last Modified 2020年10月6日
异常处理
调试python代码,常常看到这样的提示,During handling of the above exception, another exception occurred。这是如何发生的?
请看如下代码:
x = 2
y = 0
try:
result = x / y
except ZeroDivisionError:
raise ValueError('raise in exception clause')
print("=== division by zero!")
else:
print("result is", result)
finally:
raise ValueError('raise in finally clause')
print("executing finally clause")
ZeroDivisionError必然发生,然后代码进入except分支,在这个分支中,遇到了一个raise,后面的print得不到执行。由于有finally分支,在raise之前,需要执行finally分支的代码,不幸的是,此时又遇到了raise,它后面的print也得不到执行。因此运行这段代码的效果,就是如下:
E:\py>python try.py
Traceback (most recent call last):
File "try.py", line 8, in
result = x / y
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "try.py", line 10, in
raise ValueError('raise in exception clause')
ValueError: raise in exception clause
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "try.py", line 15, in
raise ValueError('raise in finally clause')
ValueError: raise in finally clause
这就是During handling of the above exception, another exception occurred的由来!在处理异常的except分支或离开try的finally分支有raise,就会出现这样的提示。
到此,自然而然我们会想到另一个问题,在这种情况下,如果这段代码整体有try护着,抛出来的异常时哪个呢?请看下面的测试代码:
def testA():
x = 2
y = 0
try:
result = x / y
except ZeroDivisionError:
raise ValueError('raise in exception clause')
print("=== division by zero!")
else:
print("result is", result)
finally:
raise ValueError('raise in finally clause')
print("executing finally clause")
try:
testA()
except Exception as e:
print(repr(e))
运行结果:
E:\py>python try.py
ValueError('raise in finally clause')
看出来了吧,抛出来的只有最后那一个exception!
-- EOF --
本文链接:https://www.pynote.net/archives/1856
《During handling of the above exception, another exception occurred是如何发生的?》有1条留言
前一篇:用python有效获取本机IP地址
后一篇:编译python代码
Ctrl+D 收藏本页
©Copyright 麦新杰 Since 2019 Python笔记
本文示例中的两个above exception,应该就是指ZeroDivisionError。except和finally分支中的两个raise,没有处理代码,会被直接抛出。提示中说的“在处理的异常”,只有ZeroDivisionError。 [ ]