Skip to main content
 首页 » 编程设计

python之为什么用try :捕获异常时不能返回

2025年05月04日14xxx_UU

我想在捕获异常时在某些情况下从函数返回:

def myfunc(): 
    try: 
        a = 1 
    except: 
        pass 
    else: 
        if a == 1: 
            return a 
    finally: 
        return 100 
 
x = myfunc() 
print(x) 

我对上面代码的期望是

  • try 成功(未引发异常)
  • 转到满足条件的else
  • 从函数返回a,其余代码没有运行

如您所想,我得到的结果是 100,这意味着 finally 子句已被评估。

因为我显然遗漏了一些东西,所以我通过调试器运行了它,我确实到达了 return a 行,但实际上并没有在那个时候返回。

请您参考如下方法:

finally 总是 执行。您返回得很好,只是您误解了 finally 套件做的事情。

来自try statement documentation :

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.’

在此上下文中,except 和 else 处理程序仍然是 try 套件的一部分。

finally 套件用作清理处理程序;一旦进入 try 套件,无论发生什么情况,finally 都会被执行。这也意味着您可以更改返回的内容。这是明确记录的:

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:

>>> 
>>> def foo(): 
...     try: 
...         return 'try' 
...     finally: 
...         return 'finally' 
... 
>>> foo() 
'finally'