python: [try + except] How to make sure all command under try is executed?
<p>This is a very beginners' question. But I cannot find answer...</p>

<p>I want to run <strong>ALL</strong> lines under <code>try</code>. If <strong>ANY</strong> lines are unexecutable, run <code>except</code>. </p>

<p>For example, I have some codes like this...</p>

<pre><code>for i in range(0,100):
    try:
        print "a"
        print "b"
        print i, C
        print "d"
    except:
        print i, "fail"
</code></pre>

<p>I want to have <strong>ALL</strong> the lines under <code>try</code> executed. In this example, <code>print C</code> is unexecutable, because <code>C</code> is not pre-defined. </p>

<p>Thus, I want to <strong>ONLY</strong> run <code>print i, "fail"</code> under <code>except</code>, because <code>NOT ALL</code> lines under <code>try</code> are executable.</p>

<p>To be more clearly, The code above gives me the result: </p>

<pre><code>a
b
0 0 Fail
a
b
1 1 Fail
a
b
2 2 Fail
...
</code></pre>

<p>But I want to have a result like this:</p>

<pre><code>0 Fail
1 Fail
2 Fail
...
</code></pre>

<p>How can I do this? Thanks. </p>

<p><strong>UPDATE:</strong><br>
To be more clearly, I am not asking for a result, I am asking for a method. I think there should be some commands to control <code>try</code>. </p>

<p>This is very similar to what @trincot posted, not sure if it would meet your requirements.</p>

<p>Basically, move all of your prints to a separate function and call that in your try.</p>

<pre><code>def printer(i=None, C=None):
    print "a"
    print "b"
    print i, C
    print "d"    

for i in range(0,100):
    try:
        printer(i, C)
    except:
        print i, "fail"
</code></pre>

python