Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python try except yield combination

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'
like image 970
nos Avatar asked Dec 14 '22 03:12

nos


1 Answers

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
like image 97
brianpck Avatar answered Dec 27 '22 00:12

brianpck