python try except yield combination

nos picture nos · Oct 11, 2016 · Viewed 8.2k times · Source

I use function f to create generator but sometimes it can raise error. I would like two things to happen for the main code

  1. The for loop in the main block continues after catching the error
  2. In the except, print out the index that generates the error (in reality the error may not occur for index 3)

The code I came up with stops after the error is raised. How shall I implement the forementioned two features? Many thanks.

def f(n):
    for i in xrange(n):
        if i == 3:
            raise ValueError('hit 3')
        yield i

if __name__ == '__main__':
    a = enumerate(f(10))
    try:
        for i, x in a:
            print i, x
    except ValueError:
        print 'you have a problem with index x'

Answer

brianpck picture brianpck · Oct 11, 2016

You will have to catch the exception inside your generator if you want its loop to continue running. Here is a working example:

def f(n):
    for i in xrange(n):
        try:
            if i == 3:
                raise ValueError('hit 3')
            yield i
        except ValueError:
            print ("Error with key: {}".format(i))

Iterating through it like in your example gives:

>>> for i in f(10):
...     print (i)
...
0
1
2
Error with key: 3
4
5
6
7
8
9