Python尝试最终阻止返回 [英] Python try finally block returns

查看:116
本文介绍了Python尝试最终阻止返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是有趣的代码:

def func1():
    try:
        return 1
    finally:
        return 2

def func2():
    try:
        raise ValueError()
    except:
        return 1
    finally:
        return 3

func1()
func2()

请有人解释一下,什么结果将返回这两个函数并解释原因,即描述执行顺序

Could please somebody explain, what results will return these two functions and explain why, i.e. describe the order of the execution

推荐答案

从Python 文档

无论是否发生异常,总是在离开try语句之前执行finally子句.当try子句中发生异常且未由except子句处理(或在except或else子句中发生)时,将在执行finally子句后重新引发该异常.当try语句的任何其他子句通过break,continue或return语句离开时,finally子句也会在出路"上执行.一个更复杂的示例(在同一try语句中具有except和finally子句从Python 2.5开始有效):

A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. When an exception has occurred in the try clause and has not been handled by an except clause (or it has occurred in a except or else clause), it is re-raised after the finally clause has been executed. The finally clause is also executed "on the way out" when any other clause of the try statement is left via a break, continue or return statement. A more complicated example (having except and finally clauses in the same try statement works as of Python 2.5):

因此,一旦使用 return 离开了try/except块,这会将返回值设置为给定值-最终,这些块将始终执行,并应用于释放资源等,而在此使用另一种回报-覆盖原始回报.

So once the try/except block is left using return, which would set the return value to given - finally blocks will always execute, and should be used to free resources etc. while using there another return - overwrites the original one.

在您的特定情况下,func1()返回2func2()返回3,因为这些是finally块中返回的值.

In your particular case, func1() return 2 and func2() return 3, as these are values returned in the finally blocks.

这篇关于Python尝试最终阻止返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆