try/except/finally

Ian Kelly ian.g.kelly at gmail.com
Sun Jun 8 14:07:34 EDT 2014


On Sun, Jun 8, 2014 at 12:02 PM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> On Sun, Jun 8, 2014 at 11:57 AM, Joshua Landau <joshua at landau.ws> wrote:
>> On 8 June 2014 08:12, Marko Rauhamaa <marko at pacujo.net> wrote:
>>>
>>> Does anyone have an example motivating a return from finally? It seems
>>> to me it would always be a bad idea as it silently clears all unexpected
>>> exceptions.
>>
>> In a general sense:
>>
>>     try:
>>         something_that_can_break()
>>         return foo() # before clean_up
>>     finally:
>>         clean_up()
>>         if default:
>>             return default() # after clean_up()
>>
>> What's the best replacement? Note: I've never done this.
>
> Why not just move the default out of the finally block?
>
>     try:
>         something_that_can_break()
>         return foo() # before clean_up
>     finally:
>         clean_up()
>     if default:
>         return default() # after clean_up()

Never mind, that doesn't work.  But you could do this:

    try:
        something_that_can_break()
        return foo() # before clean_up
    except ExpectedException:
        if default:
            return default() # after clean_up()
        else:
            raise
    finally:
        clean_up()

And then anything unexpected will be propagated instead of silenced.



More information about the Python-list mailing list