Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing exceptions from terminating Python iterator

Tags:

python

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?

like image 324
Cerin Avatar asked Dec 26 '22 04:12

Cerin


1 Answers

The generator needs to handle the exception within itself; it is terminated if it raises an unhandled exception, just like any other function.

like image 89
kindall Avatar answered Jan 05 '23 00:01

kindall