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异常?
目前没有回答
相关问题 更多 >
编程相关推荐