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?
The generator needs to handle the exception within itself; it is terminated if it raises an unhandled exception, just like any other function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With