python try except yield combination
<p>I use function <code>f</code> to create generator but sometimes it can raise error. I would like two things to happen for the main code</p>

<ol>
<li>The <code>for</code> loop in the main block continues after catching the error</li>
<li>In the <code>except</code>, print out the index that generates the error (in reality the error may not occur for index 3)</li>
</ol>

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

<pre><code>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'
</code></pre>

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

<pre><code>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))
</code></pre>

<p>Iterating through it like in your example gives:</p>

<pre><code>&gt;&gt;&gt; for i in f(10):
...     print (i)
...
0
1
2
Error with key: 3
4
5
6
7
8
9
</code></pre>

python try-catch yield except