11

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?'

3 Answers 3

10

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
Sign up to request clarification or add additional context in comments.

2 Comments

In this simple case probably yes. But what if we want a function where iteration is stopped by default but we can continue with the next item catching an exception? We should have an external signal that something is wrong.
@sergzach: We could do something like yield None instead of pass and catch that special case in the caller.
2

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

Comments

1

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))
   ...:     

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.