[Python-ideas] Make return inside a finally a SyntaxError

Nick Coghlan ncoghlan at gmail.com
Sat Jul 18 16:01:32 CEST 2009


Michael Foord wrote:
> I was surprised - I *thought* the semantics of finally were well
> defined; that exceptions inside the try block will be propagated unless
> a new exception is raised inside the finally. That return (and break it
> transpires) silently and implicitly swallow those exceptions is surprising.
> 
> It is also *odd*. If you *want* behavior then it is trivial to use an
> except instead of a finally, so I don't see a use case for it.

I think the perception of whether this behaviour is odd or not depends
on your perception of how a finally block works. If you just see it as a
normal sequence of instructions with an implicit "re-raise current
exception" at the end of the normal flow of control, then the fact that
return, break and raise can all bypass that re-raise by exiting the
block differently isn't particularly surprising (the only surprising
thing is that this doesn't also hold for continue).

However, if your mental model is that finally blocks are special
sections of code that promise to reraise the exception *even if* the
finally block exits by a means other than control flowing off the end,
then I can see why the current behaviour would be surprising.

This sounds like a documentation problem to me - the explanation of the
finally block in the tutorial and language reference should be pushing
people towards the first interpretation, since it is the one actually
used by the language.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------



More information about the Python-ideas mailing list