def simple_generator():
print("-> start ..")
try:
x = yield
print("-> receive {} ..".format(x))
except StopIteration:
print("simple_generator exit..")
我知道next对生成器对象的每次调用都会运行代码,直到下一个 yield 语句,并返回产生的值。如果没有更多可以得到,StopIteration则被提出。
所以我想将StopIterationin 函数simple_generator作为上面的代码来捕获。然后我尝试了:
>>>
>>> sg3 = simple_generator()
>>> sg3.send(None)
-> start ..
>>> sg3.send("hello generator!")
-> receive hello generator! ..
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
它确实抛出StopIteration了,而try ...excepdit根本没有抓住它,我不明白根本原因是什么,有人能解释一下吗?提前致谢。
当然,我也知道,例如,如果我处理StopIteration函数外的异常simple_generator,它确实可以按我的预期工作。
>>> try:
... sg4 = simple_generator()
... while True:
... next(sg4)
... except StopIteration:
... print("sg4 exit ..")
...
-> start ..
-> receive None ..
sg4 exit ..
>>>
所以我的问题是为什么我们不能在生成器确定函数中捕获 Stopiteration 异常?