try...finally is more powerful than I thought.

Peter Hansen peter at engcorp.com
Fri Nov 7 14:08:16 EST 2003


Mauro Cicognini wrote:
> 
> I've always wondered, how does one use this in real life?
> Since I cannot write try... except... finally..., which would be the
> most intuitive construct to me, I understand I should write
> try:
>         try:
>                 ...
>         finally:
>                 ...
> except:
>         ...
> 
> to achieve the same effect.
> 
> Am I right? I.e. (again) how do you people use try .. finally in real
> use cases?

I use the above in the exceptionally rare case where I really want
that particular behaviour: cleanup prior to unrelated exception handling.

Normally what I want is cleanup, leaving exception handling to the calling
code, in which case I just need a finally.

More often I want exception handling, and don't need cleanup, so of course
just the except clause will do.

And only slightly more often than the first case, but much less often
than the other two, I want exception handling but an overall cleanup,
in which case I use the above nested format but with the finally on
the outside and the except on the inside.

> Does anyone else think Python could have a nicer syntax for this one?

Perhaps, but it's such an incredibly insignificant thing as far as 
I'm concerned that after hearing of the existence of lengthy past 
discussions about this, and the near certainty it will not be changed,
I stopped wasting my time worrying about it and went back to writing 
code that worked, and some that didn't :-).

(Basically, check the archives for the reasons this is the way it is.)

-Peter




More information about the Python-list mailing list