gpt4 book ai didi

python - GeneratorExit,close() 不会导致回溯/异常 - 怎么样?

转载 作者:太空宇宙 更新时间:2023-11-03 11:23:36 25 4
gpt4 key购买 nike

def receiver():
print("Ready to receive")
# try:
while True:
n = (yield)
print("Got %s" % n)
# except GeneratorExit:
# print("Receiver done")

r = receiver()
r.next()

r.send(10)

r.close()

当我注释掉 GeneratorExit 时,close() 不会生成回溯!为什么?但是,随着 except 处于事件状态,我能够捕获 GeneratorExit。这怎么可能?

如果 GeneratorExit 是一个异常,那么它应该像所有其他异常一样运行并传播它正在做的事情 - 因此我能够使用 except 捕获它。但是肯定没有 except 父 python 解释器应该像所有其他异常一样捕获回溯。这里发生了什么魔法?

最佳答案

参见 generator.close() documentation .

声明 StopIterationGeneratorExit 异常在内部用于指示生成器如何退出,因此是唯一不会传播给调用者的异常。

因此,如果您想重新引发一个GeneratorExit 异常,您可能必须捕获它并将其封装在另一个自定义异常中。

关于python - GeneratorExit,close() 不会导致回溯/异常 - 怎么样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38091111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com