You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中try、except、finally执行疑问:为何finally覆盖try返回值?

Python中try块返回值被finally块覆盖的原因

我运行以下Python代码:

def finding(a,b):

    try:
        result=a+b
        return result
    except TypeError:
        return "please type only num"
    finally:
        return "this line will get print at last"

print(finding (5, 2)) 

得到的是finally块的输出,却没有得到try块的输出,请问这是什么原因?


原因解析

  • 在Python里,finally块的执行逻辑是无论try/except块是否触发异常、是否执行return,它都会被执行。
  • 当try块里执行return result时,Python会先暂存result的值,但不会立刻完成函数返回,而是先跳转执行finally块的代码。
  • 如果finally块中存在return语句,这个return会直接替换掉之前暂存的返回值,函数最终会返回finally块里的内容,try块的返回值会被直接丢弃。

简单总结:finally中的return会直接抢占函数的最终返回结果,覆盖掉try/except块里的返回值。


内容的提问来源于stack exchange,提问作者Mohit Mishra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 08:25:13