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

Python中finally块是否一定会执行?存在例外场景吗?

Will a Python try-finally Block's finally Clause Always Execute?

Great question—this is a common point of confusion, and your testing is spot-on: in most typical scenarios (like returning from an except block, re-raising exceptions, or even using sys.exit()), the finally clause will absolutely run before the control flow leaves the try statement.

But there are a handful of edge cases where finally won't execute. Let's break them down:

  • The Python interpreter crashes catastrophically: If your code triggers a low-level error that takes down the interpreter entirely (like a segmentation fault from a buggy C extension, or using the low-level os._exit() function which terminates the process immediately without cleaning up), there's no chance for the interpreter to run the finally clause.
  • The process is killed externally: If the operating system or another force terminates your Python process (e.g., using kill -9 on Unix, or ending the task via Task Manager on Windows), the process stops instantly—Python never gets to the point of executing the finally block.
  • An infinite loop in the try/except block: If your code gets stuck in an infinite loop inside the try or except section, the program never reaches the point where it would exit those blocks and run finally. This isn't so much "not executing" as "never getting to the execution point."

It's worth clarifying one common misconception: calling sys.exit() does trigger finally. That's because sys.exit() raises a SystemExit exception, which is handled like any other—finally runs before the exception propagates and exits the program. Here's a quick test to confirm:

import sys
try:
    print("In try block")
    sys.exit()
finally:
    print("Finally executed!")

Running this will print both lines, proving finally runs even with sys.exit().

In short: for all normal Python control flows (including exceptions, returns, and sys.exit()), finally is guaranteed to run. Only extreme, external, or catastrophic events can prevent it.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 09:16:20