Try-except-finally paradox
wxjmfauth at gmail.com
wxjmfauth at gmail.com
Thu Jan 30 01:59:09 EST 2014
Le jeudi 30 janvier 2014 06:56:16 UTC+1, Jessica Ross a écrit :
> 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 paradox is, in my mind, that the fct paradox() is
programmed to be paradoxal.
Compare with:
>>> def noparadox(i):
... try:
... a = 1 / i
... print('Process')
... except ZeroDivisionError:
... print("ZeroDivisionError")
... a = '?'
... except Exception:
... print("Exception")
... a = '?'
... finally:
... print("Finally")
... return a
...
>>> noparadox(2)
Process
Finally
0.5
>>> noparadox(0)
ZeroDivisionError
Finally
'?'
>>> noparadox('asdf')
Exception
Finally
'?'
>>>
jmf
More information about the Python-list
mailing list