Sub topic 7
Guaranteed cleanup with finally
This chapter assumes you can write functions, use try and except, and read a basic traceback. It covers what finally guarantees, how it behaves on each exit path, and the mistakes that make it dangerous.
What finally guarantees
A finally clause holds code that runs no matter how the try statement ends. It runs after a normal finish, after a handled exception, after an unhandled exception, and after a return. Use it for cleanup that must happen, such as closing a file, releasing a lock, or restoring state.
def parse_port(text):
try:
port = int(text)
except ValueError:
print(f"{text!r} is not a number")
return None
else:
if not 0 < port < 65536:
raise ValueError(f"port out of range: {port}")
return port
finally:
print("parse_port finished")
print(parse_port("8080"))
print(parse_port("abc"))The try block holds only the risky int() call. The else block runs only when no exception occurred. The finally block runs on every path, including the early return None. The output shows parse_port finished before each returned value is printed, because the function must finish its cleanup before the caller receives the result.
The order of events
When an exception is not caught, Python runs the finally block first and then continues propagating the exception up the call stack. The cleanup happens on the way out.
Cleanup by hand
Before context managers, try and finally were the standard way to release a resource. This pattern is still the foundation of every with statement.
f = open("notes.txt")
try:
first_line = f.readline()
finally:
f.close()Open the resource before the try. If open() itself fails, there is nothing to close, and putting it inside the try would make finally call close() on a name that was never assigned.
How return, break, and continue interact
A return inside try does not exit immediately. Python evaluates the return value, runs finally, and then returns. A return, break, or continue placed inside finally is a different matter. It overrides whatever was pending.
def swallow():
try:
raise RuntimeError("lost")
finally:
return "finally wins"
print(swallow())This prints finally wins. The return in finally discards the pending RuntimeError, so the error vanishes with no traceback and no log entry.
Common mistakes
- Putting too much in
finally. Code that can itself raise may replace the original exception. Keep cleanup short and safe. - Acquiring the resource inside
try, then cleaning up a name that does not exist. - Using
finallyfor logic that belongs inelse. If code should run only on success, it does not belong infinally. - Expecting
finallyto run when the process is killed. It does not run afteros._exit()or a hard kill.
Choosing between the clauses
| Clause | Runs when | Typical use |
|---|---|---|
| `except` | A matching exception was raised | Recover or translate the error |
| `else` | The `try` block raised nothing | Success-path code |
| `finally` | Always | Release resources |
Exercise
What does this function return, and is "cleanup" printed before or after the value is returned to the caller? def f(): try: return "try" finally: print("cleanup")
Show answer
It returns "try". The text "cleanup" is printed first, because Python evaluates the return value, runs the finally block, and only then hands the value to the caller.
Exercise
Why is it a problem to write return inside a finally block when the try block raised an exception?
Show answer
The return discards the pending exception, so the error is silently lost. The caller gets a normal return value and never sees a traceback.