Reputation: 64719
How do you prevent exceptions from prematurely terminating a Python generator/iterator?
For example, consider the following:
#!/usr/bin/env python
def MyIter():
yield 1
yield 2
yield 3
raise Exception, 'blarg!'
yield 4 # this never happens
my_iter = MyIter()
while 1:
try:
value = my_iter.next()
print 'value:',value
except StopIteration:
break
except Exception, e:
print 'An error occurred: %s' % (e,)
I would expect the output:
value: 1
value: 2
value: 3
An error occurred: blarg!
value: 4
However, after the exception, the iterator terminates and value 4 is never yielded even though I've handled the exception and haven't broken my loop. Why is it behaving this way?
Upvotes: 5
Views: 123
Reputation: 184151
The generator needs to handle the exception within itself; it is terminated if it raises an unhandled exception, just like any other function.
Upvotes: 8
Reputation: 11686
You need to handle whatever exception might occur in the generator:
def MyIter():
yield 1
yield 2
yield 3
try:
raise Exception, 'blarg!'
except Exception:
pass
yield 4 # this will happen
Upvotes: 2