为什么我们不能在生成器定函数中捕获Stopiteration异常?

时间:2019-03-21 14:52:03

标签: python coroutine

def simple_generator():
    print("-> start ..")
    try:
        x = yield
        print("-> receive {} ..".format(x))
    except StopIteration:
        print("simple_generator exit..")

我知道在生成器对象上对next的每次调用都会运行代码,直到下一个yield语句为止,并返回yielded值。如果没有其他东西,将引发StopIteration

因此,我想捕获函数StopIteration中的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 ...excep根本没有抓住它,我不明白根本原因是什么,有人可以解释吗?预先感谢。

当然,我也知道,如果我在函数StopIteration外部处理了simple_generator异常,那么它确实按预期运行。

>>> try:
...     sg4 = simple_generator()
...     while True:
...         next(sg4)
... except StopIteration:
...     print("sg4 exit ..")
...
-> start ..
-> receive None ..
sg4 exit ..
>>>

所以我的问题是为什么我们不能在生成器定函数中捕获Stopiteration异常?

0 个答案:

没有答案
相关问题