在编写高质量代码-改善python程序的91个建议中有一个关于try-finally的一个问题如下:
def ReturnTest(a):
try:
if a <= 0:
raise ValueError('data can not be negative')
else:
return a
except ValueError as e:
print(e)
finally:
print('the end')
return -1
ReturnTest(0)
ReturnTest(2)
给入参数为0时,输出结果可以解释通,输入参数为2时,就想不通了,书中解释说是在执行return a
之前会先执行finally
代码块,这是为何?
This is expected behavior: no matter what happens, the finally block will always execute, even if you return it.
PS: This book seems to be the one that I couldn’t read at the beginning because I thought the quality was too poor.
In
try-except, when the
try
statement in thereturn
block is executed, it will automatically jump to thefinally
block for execution. When the execution infinally
is completed, then entertry
Executereturn
in . To this end, I made a test:You can see the conclusion just now from the output results
This is the same as java,
finally
Add it, it is what you must do!This is not a pitfall, but the design of the language, this is a grammatical rule, just like Python requires indentation.