python - try-finally中的1个坑
天蓬老师
天蓬老师 2017-04-17 15:00:13
0
3
421

在编写高质量代码-改善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代码块,这是为何?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(3)
Peter_Zhu

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 the return block is executed, it will automatically jump to the finally block for execution. When the execution in finally is completed, then enter try Execute return in . To this end, I made a test:

def test():
    try:
        print(666)
        return 1
    finally:
        print(777)


>>> test()
666
777
1

You can see the conclusion just now from the output results

小葫芦

This is the same as java, finallyAdd 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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!