Python中finally块是否一定会执行?存在例外场景吗?
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 thefinallyclause. - The process is killed externally: If the operating system or another force terminates your Python process (e.g., using
kill -9on Unix, or ending the task via Task Manager on Windows), the process stops instantly—Python never gets to the point of executing thefinallyblock. - An infinite loop in the
try/exceptblock: If your code gets stuck in an infinite loop inside thetryorexceptsection, the program never reaches the point where it would exit those blocks and runfinally. 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

