Handle an exception thrown in a generator

When a generator throws an exception, it exits. You can’t continue consuming the items it generates.

Example:

>>> 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.

Leave a Comment