I use function f
to create generator but sometimes it can raise error. I would like two things to happen for the main code
for
loop in the main block continues after catching the errorexcept
, 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'
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