python - 为什么我们无法在生成器确定函数中捕获 Stopiteration 异常?
问题描述
def simple_generator():
print("-> start ..")
try:
x = yield
print("-> receive {} ..".format(x))
except StopIteration:
print("simple_generator exit..")
我知道next
对生成器对象的每次调用都会运行代码,直到下一个 yield 语句,并返回产生的值。如果没有更多可以得到,StopIteration
则被提出。
所以我想将StopIteration
in 函数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
dit根本没有抓住它,我不明白根本原因是什么,有人能解释一下吗?提前致谢。
当然,我也知道,例如,如果我处理StopIteration
函数外的异常simple_generator
,它确实可以按我的预期工作。
>>> try:
... sg4 = simple_generator()
... while True:
... next(sg4)
... except StopIteration:
... print("sg4 exit ..")
...
-> start ..
-> receive None ..
sg4 exit ..
>>>
所以我的问题是为什么我们不能在生成器确定函数中捕获 Stopiteration 异常?
解决方案
推荐阅读
- reactjs - 为什么传递给子组件的变量没有被更新?
- r - AGOL 托管要素服务返回的要素多于 maxRecordCount
- ckeditor - 如何在CKEditor(IE问题)中动态更改可编辑区域中的光标图标?
- vue.js - 如何在嵌套在方法下的forreach循环中访问和设置vue.js的属性
- loops - 循环记录年份
- sql - 从每日粒度的事实表计算日期间隔
- c# - WPF(VS2012):为什么应用程序中窗口的外观会根据其安装的系统而改变?
- python - 将这些价格和日期数组存储在熊猫数据框中
- sql - Oracle SQL in 子句 - 速度慢
- python - sqlalchemy 中的连接池是线程安全的吗?