else: w/o except: - why not?

Robin Munn rmunn at pobox.com
Wed Apr 2 10:58:22 EST 2003


Anna <revanna at mn.rr.com> wrote:
> On Tue, 01 Apr 2003 07:33:57 +0000, Michael Chermside wrote:
> 
>> I can't speak for Tim, but my OWN opinion is precisely in alignment with
>> what you have written.
>> 
>> I think that a "bare except" is useful in only two ways. The first is like
>> a "finally" clause that's skipped if everything works. In other words, the
>> following bits of code is (almost[1]) equivalent to your second example:
>> 
>>     everythingWorked = False
>>     try:
>>         f1()
>>         everythingWorked = True
>>     finally:
>>         if not everythingWorked:
>>             f2()
>> 
>> This doesn't come up much, but it's occasionally useful, and your version
>> (using bare except with a raise) is a little prettier.
> 
> I thought that finally clauses are *always* run, whether an exception was
> raised or not. 
> 
> Looks at code closely... So, in this case the finally is run (in terms of
> evaluating the "if" statement), but function f2 may not happen depending
> on the results of the "if". So the finally isn't really skipped, it just
> doesn't do much if everything worked properly in the try clause. Right?
> 
> I'm not being picky - just seeing if I understand this correctly. Thanks.

Yes, you've got it right. If an exception is raised during f1(), then
the "everythingWorked = True" line is never reached, because program
execution flow jumps to the finally: clause, which would then call f2()
because everythingWorked is still False. Note that after any finally:
clause is executed, the exception then continues to propagate upwards.
If f1() raised no exceptions, then the finally: clause is still
executed, but this time everythingWorked is True, so f2() is not called.

The way to express that using try...except is:

    try:
        f1()
    except:
        f2()
        raise

-- 
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838    50FF 2478 CFFB 081A 8338  54F7 845D ACFD 6AFB 6838




More information about the Python-list mailing list