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