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

Stephen J. Turnbull stephen at xemacs.org
Sat Jul 18 16:14:59 CEST 2009


Michael Foord writes:

 > I think the current behavior (swallowing an exception that most people would
 > expect to be re-raised) surprises and pisses people off. Guido has already
 > made a pronouncement so not much point continuing this discussion.

If you say so.  I think that there's an education and documentation
issue here, though.  You write elsewhere:

    Finally is normally dead simple but the explanation usually
    includes what it does with exceptions:

    Finally is *always* run last. Exceptions that occur in the try
    block are re-raised once the finally has completed. Exceptions
    inside the finally block will be re-raised

[Isn't that wrong?  An exception in the finally block will terminate
the finally block, no?  There's no "re-"raise about it.]

    The bit that has to be *added* in Python (and usually isn't added
    because it isn't at all obvious) is:

    Exceptions are not reraised if the finally returns or breaks.

Well, yes, except that I don't think that your explanation accurately
reflects what finally is supposed to do.  I would write:

    On *all* exits from the try block, control is first transferred to
    the finally block.  If control flows off its end, the exit
    proceeds as if there had been no finally block: values are
    returned by return, exceptions are propagated to the innermost
    containing handler, and otherwise control flows to the containing
    suite.

    An exception raised (either by called code or an explicit raise)
    in a finally block will supersede a return or exception generated
    in the try block.  Control transfer constructs (break, return) in
    a finally block also supersede return statements or exceptions
    generated in the try block.

I suppose the difference from what you wrote is a reflection of
finally's heritage as a construct completely independent of
exceptions.



More information about the Python-ideas mailing list