Sub topic 8
How return, break, and continue interact with finally
This chapter assumes you can write try/except/finally statements and know how exceptions propagate. It covers what happens when control leaves a try block early, and why you should not leave a finally block early.
finally runs on every exit
A return, break, or continue inside try does not skip finally. Python pauses the jump, runs the finally block, then finishes the jump.
def fetch():
try:
return "result"
finally:
print("cleanup")
print(fetch())This prints cleanup first, then result. The return value is computed before finally runs, but the function does not hand it back until finally completes.
The same rule applies in loops:
for n in range(3):
try:
if n == 1:
continue
if n == 2:
break
print("body", n)
finally:
print("finally", n)The output is body 0, finally 0, finally 1, finally 2. Iteration 1 skips the body with continue, and iteration 2 leaves the loop with break. Both iterations still run finally.
A jump inside finally overrides the pending one
If finally itself executes return, break, or continue, it cancels whatever was pending. That includes a pending exception.
def swallow():
try:
raise RuntimeError("lost")
finally:
return "finally wins"
print(swallow())The output is finally wins. The RuntimeError is discarded with no traceback and no warning at runtime. The same thing happens to a value from an earlier return:
def override():
try:
return "from try"
finally:
return "from finally"
print(override())This prints from finally.
break and continue in finally behave the same way inside a loop:
for n in range(3):
try:
raise ValueError(n)
finally:
continue
print("loop finished without any error")Each ValueError is dropped, and the loop runs to the end.
What to do instead
Keep finally for cleanup only: closing files, releasing locks, resetting state. If you need to decide what to return or whether to suppress an error, do it outside finally.
def read_first_line(path):
f = open(path)
try:
return f.readline()
finally:
f.close()Here finally does one job and never changes control flow. If the work in finally can itself fail, handle that failure inside the block with its own try/except, so a cleanup error does not replace the original one.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| `return` in `finally` | Hides exceptions and earlier return values | Move the return after the `try` statement |
| `continue` in `finally` inside a loop | Discards the current exception | Handle the error in `except` instead |
| Assuming `finally` is skipped after `return` | Surprise output order | Remember that the return value is saved, then `finally` runs |
Exercise
What does this function return, and does the ValueError reach the caller? def f(): for i in range(2): try: raise ValueError("bad") finally: break return "done"
Show answer
It returns "done". The break in finally cancels the pending ValueError, so the exception never reaches the caller. The loop exits and execution continues to the return statement.