try/except/finally

Philip Shaw jnufcvyvuc at tznvy.pbz
Mon Jun 9 05:13:08 EDT 2014


On 2014-06-08, Dave Angel <davea at davea.name> wrote:
> Frank B <fbicknel at gmail.com> Wrote in message:
>> Ok; this is a bit esoteric.
>> 
>> So finally is executed regardless of whether an exception occurs, so states the docs.
>> 
>> But, I thought, if I <return> from my function first, that should take precedence.
>> 
>> au contraire
>> 
>> Turns out that if you do this:
>> 
>> try:
>>   failingthing()
>> except FailException:
>>   return 0
>> finally:
>>   return 1
>> 
>> Then finally really is executed regardless... even though you told it to return.
>> 
>> That seems odd to me.
>> 
>
> The thing that's odd to me is that a return is permissible inside
>  a finally block. That return
> should be at top level,  even with the finally line. And of course
>  something else should be in the body of the finally
>  block.

It does have some legitimate uses, for example:

try:
    failingThing()
finally:
    simple_cleanup()
    if(that_worked())
        return
    complicated
        cleanup
    with
        lots
            of
        blocks

OTOH, it could just be that Guido didn't think of banning it when
exceptions were first added and doesn't want to introduce an
incompatability later.



More information about the Python-list mailing list