奇怪的尝试,除了返回语句的Else Finally行为

2024-05-13 13:44:17 发布

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

这是一些行为特殊的代码。这是我写的行为的一个简化版本。这仍然会显示出奇怪的行为,我有一些具体的问题,为什么会发生这种情况。

我在Windows7上使用Python2.6.6。

def demo1():
    try:
        raise RuntimeError,"To Force Issue"
    except:
        return 1
    else:
        return 2
    finally:
        return 3

def demo2():
    try:
        try:
            raise RuntimeError,"To Force Issue"
        except:
            return 1
        else:
            return 2
        finally:
            return 3
    except:
        print 4
    else:
        print 5
    finally:
        print 6

结果:

>>> print demo1()
3
>>> print demo2()
6
3
  • 为什么demo one返回3而不是1?
  • 为什么演示2打印6而不是打印6 w/4或5?

Tags: to代码returndefissueelseraiseprint
2条回答

执行顺序为:

  1. try block all正常完成->;最后block->;函数结束
  2. 尝试块运行并进入异常A->;最终块->;函数结束
  3. try block生成返回值并调用return->;finally block->;popup return value->;函数结束

因此,finally块中的任何返回都将提前结束步骤。

因为finally语句被保证执行(假设没有断电或Python控制之外的任何事情)。这意味着在函数返回之前,它必须运行finally块,该块返回不同的值。

Python docs状态:

When a return, break or continue statement is executed in the try suite of a try…finally statement, the finally clause is also executed ‘on the way out.’

The return value of a function is determined by the last return statement executed. Since the finally clause always executes, a return statement executed in the finally clause will always be the last one executed:

这意味着当您试图返回时,将调用finally块,返回它的值,而不是您本来应该拥有的值。

相关问题 更多 >