代码
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
条款?的Python:尝试...除了......终于在发电机
请给予解释与参考。
你在'gen()'函数外面引发异常,所以它没有捕获它。并且'finally'总是被执行。 – furas
因为'finally'每次执行时代码是否失败(它就像是一个清理),并且你在异常发生器之外引发了异常,所以它不知道它 – danidee
尝试''g = gen() ; g.throw(ValueError)'''。 – wwii