Sub topic 8
How return, break, and continue interact with finally
This chapter assumes you can write try, except, and finally blocks, you know what a function's return value is, and you can read a loop with break and continue. It covers what happens when a jump statement runs inside a try block, what happens when one runs inside a finally block, and why the second case is a common source of lost errors.
The rule: finally runs on every exit
A finally block runs whenever control leaves the try statement, whatever the reason. The ways out are:
- The
trybody finishes normally. - An exception is raised, handled or not.
- A
returnstatement runs. - A
breakstatement runs. - A
continuestatement runs.
The finally block is the last thing to execute before control moves on. If the exit was a jump or an exception, Python holds that pending action, runs finally, and then resumes the action. The next sections show what "holds" means in practice.
return in a try block
When return expr runs inside try, Python evaluates expr first and stores the result. Then it runs finally. Changes made in finally do not alter the stored value.
def f():
x = 1
try:
return x
finally:
x = 2
print("finally runs, x =", x)
print(f())The output is:
finally runs, x = 2
1The function returns 1 because the value was already captured when return x executed. Rebinding the name x afterward has no effect on it.
The case is different for mutable objects. If you return a list and finally appends to that same list, the caller sees the change, because both refer to one object.
def g():
items = [1]
try:
return items
finally:
items.append(2)
print(g())This prints [1, 2].
break and continue in a try block
Inside a loop, break and continue also trigger finally. The cleanup runs once per iteration in which the try statement is entered.
for i in range(3):
try:
if i == 1:
continue
print("body", i)
finally:
print("cleanup", i)
print("loop done")The output is:
body 0
cleanup 0
cleanup 1
body 2
cleanup 2
loop doneIteration 1 skips the print("body", ...) call but still prints cleanup 1. Replace continue with break and the loop stops after cleanup 1, and finally still runs for that last iteration.
This is the behavior you want for per-item cleanup, such as releasing a lock or deleting a temporary file for each item in a batch. You do not need to repeat the cleanup code before every continue.
A jump inside finally replaces the pending action
The surprising behavior starts when finally itself contains return, break, or continue. The pending action is dropped, and the new jump takes over.
def swallow():
try:
raise RuntimeError("lost")
finally:
return "finally wins"
print(swallow())This prints finally wins. The RuntimeError is gone, with no traceback and no log entry. The caller believes the function succeeded.
The same thing happens to a return value. A return in finally overrides a return in try:
def which():
try:
return "try"
finally:
return "finally"
print(which())This prints finally.
A continue or break in finally can also cancel an exception:
for attempt in range(3):
try:
raise RuntimeError(f"attempt {attempt}")
finally:
continue
print("loop done")All three exceptions vanish, and the program prints loop done. This is almost never what the author intended.
Raising inside finally
A raise in finally does not erase the earlier exception from view. Python records it as the new exception's __context__, so the traceback shows both.
def replace():
try:
raise KeyError("original")
finally:
raise RuntimeError("from finally")
try:
replace()
except RuntimeError as exc:
print(repr(exc))
print(repr(exc.__context__))The output is:
RuntimeError('from finally')
KeyError('original')The caller receives the RuntimeError, so a handler written for KeyError will not run. The original error is still recoverable from __context__, which is why this case is less harmful than a return in finally. It still changes which exception type your callers must handle.
The usual cause is cleanup code that can itself fail, such as connection.close() on a broken connection. If the cleanup error is less important than the original one, wrap the cleanup in its own try/except:
import logging
logger = logging.getLogger(__name__)
def run(connection):
try:
connection.execute("UPDATE jobs SET done = 1")
finally:
try:
connection.close()
except Exception:
logger.exception("close failed")If execute raises, the caller still sees that error, even when close fails too.
Summary of outcomes
| What is pending | What `finally` contains | Result |
|---|---|---|
| Normal completion | Plain statements | Execution continues after the `try` statement |
| Exception | Plain statements | The exception continues to propagate |
| `return value` | Plain statements | `value` is returned, as evaluated before `finally` |
| `break` or `continue` | Plain statements | The loop jump happens after `finally` |
| Any of the above | `return`, `break`, or `continue` | The pending action is discarded and the new jump runs |
| Any of the above | `raise` | The new exception propagates, and the old one becomes its `__context__` if it was an exception |
Exits that skip or interrupt finally
finally covers nearly every exit, but a few cases are worth knowing:
sys.exit()raisesSystemExit, sofinallyblocks run as the exception propagates.os._exit()ends the process immediately, and nofinallyblocks run.- A process killed by a signal such as
SIGKILL, or by a power failure, never reachesfinally. - An infinite loop or a blocking call inside
trynever leaves thetrystatement, sofinallynever gets to run. - In a generator,
finallyruns when the generator is closed or garbage collected, which may happen later than you expect. Closing a generator raisesGeneratorExitat the pausedyield, and thefinallyblock then runs.
Practical guidance
- Use
finallyfor cleanup only: closing, releasing, restoring, or deleting. Do not put control flow there. - Put
returnin thetrybody or inelse, and keepfinallyfree ofreturn. - If cleanup can raise, guard it with its own
try/exceptand log the failure. - Prefer a
withstatement when the resource supports it. A context manager keeps the cleanup next to the resource and removes the temptation to add logic tofinally. Later chapters cover context managers. - If you see
returninfinallywhile reviewing code, treat it as a bug until proven otherwise. Run a linter that flags it, such as Ruff rule B012 (jump-statement-in-finally) from the flake8-bugbear set.
Exercises
Exercise
What does this program print, and in what order? def h(): n = 10 try: return n * 2 finally: n = 99 print("cleanup", n) print(h())
Show answer
It prints "cleanup 99" first, then 20. The return value n * 2 is evaluated to 20 before finally runs. Setting n = 99 in finally changes the name but not the value already stored for the return.
Exercise
A function opens a connection, runs a query inside try, and has "return None" inside its finally block. The query raises a TimeoutError. What does the caller see, and how would you fix the function?
Show answer
The caller sees a normal return value of None and no exception, because the return in finally discards the pending TimeoutError. To fix it, remove the return from finally so it only closes the connection. Return the result from the try body or from an else clause, and let the TimeoutError propagate.
Exercise
In a loop over files, each iteration opens a file in try and closes it in finally. One iteration uses continue when the file is empty. Does the file get closed for that iteration?
Show answer
Yes. A continue inside the try body still triggers finally before the next iteration starts, so the file is closed. The same holds for break.