Preventing exceptions from the Python terminating iterator

How do you eliminate exceptions from the premature termination of 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 an output:

 value: 1 value: 2 value: 3 An error occurred: blarg! value: 4 

However, after the exception, the iterator completes, and the value 4 never fails, although I handled the exception and did not break my loop. Why does he behave this way?

+4
source share
2 answers

The generator must handle the exception internally; it is terminated if it raises an unhandled exception, like any other function.

+8
source

You need to handle any exception that may occur in the generator:

 def MyIter(): yield 1 yield 2 yield 3 try: raise Exception, 'blarg!' except Exception: pass yield 4 # this will happen 
+2
source

All Articles