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>I suspect that, in general, you want to be able to catch values that result in error conditions. Without halting the loop inside the generator. Here's another approach that includes a Boolean in the result of the generator (as a 2-tuple) that indicates whether the calculation could be accomplished successfully.</p>

<pre><code>def f(n):
    for i in range(n):
        accept=True
        try:
            result=1/(3-i)
        except:
            accept=False
        yield accept, i

a=enumerate(f(10))
for k,(ok,i) in a:
    print (ok,i)
</code></pre>

<p>In this case, only the value 3 causes failure. Here's the output.</p>

<pre><code>True 0
True 1
True 2
False 3
True 4
True 5
True 6
True 7
True 8
True 9
</code></pre>

python try-catch yield except