Python try finally块返回

2024-04-29 20:20:34 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是有趣的代码:

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

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

func1()
func2()

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


Tags: 函数代码return顺序defraisetryvalueerror
3条回答

预先放置print语句确实有助于:

def func1():
    try:
        print 'try statement in func1. after this return 1'
        return 1
    finally:
        print 'after the try statement in func1, return 2'
        return 2

def func2():
    try:
        print 'raise a value error'
        raise ValueError()
    except:
        print 'an error has been raised! return 1!'
        return 1
    finally:
        print 'okay after all that let\'s return 3'
        return 3

print func1()
print func2()

这将返回:

try statement in func1. after this return 1
after the try statement in func1, return 2
2
raise a value error
an error has been raised! return 1!
okay after all that let's return 3
3

您会注意到python总是返回最后一个要返回的内容,而不管这两个函数中的代码“reached”return 1

一个finally块总是运行,因此在函数中返回的最后一件事是finally块中返回的任何内容。在func1中,这是2。在func2中,这是3。

它总是指向finally块,因此它将忽略tryexcept中的return。如果在tryexcept之上有一个return,它将返回该值。

def func1():
    try:
        return 1 # ignoring the return
    finally:
        return 2 # returns this return

def func2():
    try:
        raise ValueError()
    except:
        # is going to this exception block, but ignores the return because it needs to go to the finally
        return 1
    finally:
        return 3

def func3():
    return 0 # finds a return here, before the try except and finally block, so it will use this return 
    try:
        raise ValueError()
    except:
        return 1
    finally:
        return 3


func1() # returns 2
func2() # returns 3
func3() # returns 0

来自Pythondocumentation

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):

因此,一旦try/except块使用return离开,它会将返回值设置为给定的-finally块将始终execute,并应用于释放资源等,而在那里使用另一个return-覆盖原始块。

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

相关问题 更多 >