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

2024-10-01 09:40:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我知道对generator对象的每次调用next都会运行代码直到下一个yield语句,并返回生成的值。如果没有更多要获取的内容,则会引发StopIteration。你知道吗

因此,我想捕获函数simple_generator中的StopIteration作为上面的代码。然后我试着:

>>>
>>> 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它却一点也没有捕捉到,我不明白背后的原因是什么,有人能解释一下吗?提前谢谢。你知道吗

当然,我也知道,如果我在函数simple_generator之外处理StopIteration异常,它确实会像我期望的那样工作。你知道吗

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

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


Tags: 函数代码exitsimplegeneratorstartnextreceive