处理在生成器中抛出的异常 [英] Handle an exception thrown in a generator
问题描述
我有一个生成器和一个功能消耗它:
I've got a generator and a function that consumes it:
def read():
while something():
yield something_else()
def process():
for item in read():
do stuff
如果生成器抛出异常,我想在消费者函数中处理它,然后继续使用迭代器,直到它耗尽。注意,我不想在生成器中有任何异常处理代码。
If the generator throws an exception, I want to process that in the consumer function and then continue consuming the iterator until it's exhausted. Note that I don't want to have any exception handling code in the generator.
我想到了如下:
reader = read()
while True:
try:
item = next(reader)
except StopIteration:
break
except Exception as e:
log error
continue
do_stuff(item)
但这对我看起来相当尴尬。
but this looks rather awkward to me.
推荐答案
当生成器抛出异常时,它将退出。
When a generator throws an exception, it exits. You can't continue consuming the items it generates.
示例:
>>> def f():
... yield 1
... raise Exception
... yield 2
...
>>> g = f()
>>> next(g)
1
>>> next(g)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in f
Exception
>>> next(g)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
如果您控制生成器代码,可以处理生成器中的异常;如果没有,您应该尽量避免发生异常。
If you control the generator code, you can handle the exception inside the generator; if not, you should try to avoid an exception occurring.
这篇关于处理在生成器中抛出的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!