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>As of OP clarifications, he wants to continue the <strong>outside</strong> main for loop in case of error inside the generator, showing at which index the error occurred.</p>

<p>An answer by brianpck takes the approach of modifying the generator so that it prints the error. This way the main loop doesn't know an error occurred at that index, and thus you have at index x-1 the results following the error. Sometimes you care of the assumption "one index &lt;-> one result".</p>

<p>To solve this we can manually manage the error by yielding it and then deciding what to do in the generator.</p>

<p>Like to following:</p>

<pre><code>def f(n):
    for i in xrange(n):
        if i == 3:
            yield ValueError('hit 3')
            continue  # or break, depends on problem logic
        yield i

if __name__ == '__main__':
    a = enumerate(f(10))
    for i, x in a:
        if isinstance(x, ValueError):
            print "Error at index", i
            continue

        print i, x
</code></pre>

<p>Usually it's very unlikely a generator is yielding Exception classes, so it would be safe to check if the result is an Exception and dealing with it.</p>

python try-catch yield except