Try-except-finally paradox

Ian Kelly ian.g.kelly at gmail.com
Thu Jan 30 01:23:47 EST 2014


On Jan 29, 2014 11:01 PM, "Jessica Ross" <deathweasel at gmail.com> wrote:
>
> I found something like this in a StackOverflow discussion.
> >>> def paradox():
> ...     try:
> ...             raise Exception("Exception raised during try")
> ...     except:
> ...             print "Except after try"
> ...             return True
> ...     finally:
> ...             print "Finally"
> ...             return False
> ...     return None
> ...
> >>> return_val = paradox()
> Except after try
> Finally
> >>> return_val
> False
>
> I understand most of this.
> What I don't understand is why this returns False rather than True. Does
the finally short-circuit the return in the except block?

The docs don't seem to specify what happens in this case, but this behavior
is intuitive to me. If the except suite had raised an exception instead of
returning, the return in the finally would suppress that. The generalized
rule appears to be that the control flow specification executed later
overrides the earlier.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20140129/b47521c1/attachment.html>


More information about the Python-list mailing list