我有一个生成器和一个使用它的函数:
def read():
while something():
yield something_else()
def process():
for item in read():
do stuff
如果生成器抛出异常,我想在消费者函数中处理它,然后继续使用迭代器直到它耗尽。请注意,我不想在生成器中有任何异常处理代码。
我想过这样的事情:
reader = read()
while True:
try:
item = next(reader)
except StopIteration:
break
except Exception as e:
log error
continue
do_stuff(item)
但这对我来说看起来很尴尬。
最佳答案
当生成器抛出异常时,它会退出。你不能继续消费它生成的元素。
例子:
>>> 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
如果你控制了生成器代码,你可以在生成器内部处理异常;如果没有,你应该尽量避免发生异常。
关于python - 处理生成器中抛出的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11366064/