Best way to handle exceptions with try/finally

Zameer perlefar at gmail.com
Thu May 25 00:52:57 CEST 2006


> I tend to put "return"
> statements at the end of functions to make an attempt at being clean.  I
> realize that a lot of the time functions will just return but I was
> hoping by explicitly stating my function returns that another person
> reading my code would more easily see any exit points in my code.  Turns
> out that it came to bite me later.

You can put the return statement at the end.

    try:
        stuff()
    finally:
        cleanup()
    return

The return statement is not necessary in this case, but it's not in the
finally part either. If you like it, keep it. Just don't make it part
of finally if you want exceptions to propagate.

I can see where you are going by making the return statement part of
finally, and I actually expected it to work the same as if it was not
part of finally. Turns out it doesn't. Can somebody please comment on
how this works in other languages? I know that finally is not a part of
standard C++ but Borland and Microsoft compilers allow use of the
keyword __finally. Delphi also has finally and I seem to recall that
returning from the finally part does not prevent the exception from
propagating, but memory may not serve me right.

Thank you for "raising" this quite interesting question.




More information about the Python-list mailing list