Try-except-finally paradox
Dave Angel
davea at davea.name
Thu Jan 30 07:05:15 EST 2014
Jessica Ross <deathweasel at gmail.com> Wrote in message:
> 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 finally has to happen before any return inside the try or the
except. And once you're in the finally clause you'll finish it
before resuming the except clause. Since it has a return, that
will happen before the other returns. The one in the except block
will never get reached.
It's the only reasonable behavior., to my mind.
--
DaveA
More information about the Python-list
mailing list