【发布时间】:2025-11-23 11:55:02
【问题描述】:
代码
def gen():
try:
for i in range(5):
yield i
except Exception as e:
print('Caught: ' + str(e))
finally:
print('I am done')
for x in gen():
print(x)
if x == 2:
raise Exception('Catch me?')
输出
0
1
2
I am done
Traceback (most recent call last):
File "test.py", line 13, in <module>
raise Exception('Catch me?')
Exception: Catch me?
问题
为什么代码执行finally子句而不执行except子句?
请结合参考资料进行说明。
【问题讨论】:
-
您在
gen()函数之外引发异常,因此它不会捕获它。并且finally总是被执行。 -
因为
finally每次无论代码是否失败都会执行(就像清理一样),并且您在生成器外部而不是内部引发了异常,所以它不知道它 -
试试 -
g = gen(); g.throw(ValueError).
标签: python exception generator