Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Continue after exception raising in iterator/generator in python

Is there any way in Python to continue iterating after exception throwed by iterator/generator? Like in code below, is there any way to skip ZeroDivisionError and continue looping through gener() without modyfying run() function?

def gener():
    a = [1,2,3,4,0, 5, 6,7, 8, 0, 9]
    for i in a:
        yield 2/i

def run():
    for i in gener():
        print i

#---- run script ----#

try:
    run()
except ZeroDivisionError:
    print 'what magick should i put here?'
like image 604
Krzysiek Grzembski Avatar asked Sep 19 '11 14:09

Krzysiek Grzembski


3 Answers

The logical place for the try/except would be the place where the offending calculation takes place:

def gener():
    a = [1,2,3,4,0, 5, 6,7, 8, 0, 9]
    for i in a:
        try:
            yield 2/i
        except ZeroDivisionError:
            pass
like image 79
Tim Pietzcker Avatar answered Nov 03 '22 01:11

Tim Pietzcker


One possible solution is just wrapping the problem code into try ... except block:

def gener():
    a = [1,2,3,4,0, 5, 6,7, 8, 0, 9]
    for i in a:
        try:
            div_result = 2/i
        except ZeroDivisionError:
            div_result = None

        yield div_result
like image 24
Aliaksei Ramanau Avatar answered Nov 02 '22 23:11

Aliaksei Ramanau


I am not sure, but maybe this suits you better if you want to still understand where errors occured:

In [1]: def gener():
   ...:     a = [1, 2, 0, 3, 4, 5, 6, 7, 8, 9]
   ...:     errors = []
   ...:     for idx, i in enumerate(a):
   ...:         try:
   ...:             yield 2 / i
   ...:         except ZeroDivisionError:
   ...:             errors.append('ZeroDivisionError occured at idx = {}'.for
   ...: mat(idx))
   ...:     if errors:
   ...:         raise RuntimeWarning('\n'.join(errors))
   ...:     
like image 38
zhukovgreen Avatar answered Nov 02 '22 23:11

zhukovgreen