Try-except-finally paradox

Andrew Berg robotsondrugs at gmail.com
Thu Jan 30 01:33:44 EST 2014


On 2014.01.29 23:56, Jessica Ross 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?
> 
My guess would be that the interpreter doesn't let the finally block get skipped under any circumstances, so the return value gets set to
True, but then it forces the finally block to be run before returning, which changes the return value to False.

-- 
CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 10.0



More information about the Python-list mailing list