return from finally clause
Tim Peters
tim.one at home.com
Fri Jun 8 17:31:46 EDT 2001
[Jürgen Hermann]
> Consider this script:
>
> def spam(ret):
> try:
> print 1
> try:
> print 2
> raise RuntimeError
> finally:
> print 3
> if ret: return
> finally:
> print 4
> print 5
>
> spam(1)
> spam(0)
>
> and its output
>
> 1
> 2
> 3
> 4
> 1
> 2
> 3
> 4
> Traceback (most recent call last):
> File "exp.py", line 15, in ?
> spam(0)
> File "exp.py", line 6, in spam
> raise RuntimeError
> RuntimeError
>
> That means that if you (accidently?) return within a finally clause, you
> effectively eat the exception.
It also means that if you deliberately return within a finally clause, you
deliberately eat the exception. This is like saying that if you add one to
a number accidentally, the number's value increases anyway <wink>.
> This should be documented, or fixed.
Aren't the docs already clear?:
http://www.python.org/doc/current/ref/try.html
...
If the finally clause raises another exception or executes a
return or break statement, the saved exception is lost.
...
When use a finally block, you're explictly saying "NO MATTER WHAT--
exception or no exception --do the stuff in this block". If that stuff
includes a return, Python returns. You'll find the same behavior in Java
(among others).
More information about the Python-list
mailing list