Module 12 · Exception Handling — topic 7 of 11
finally
The finally clause: cleanup code that always runs — after success, after a handled error, after an unhandled error and even after return — plus how with statements automate the same idea.
Learning objectives
- Use finally for guaranteed cleanup
- Predict the order of output when finally and return interact
- Recognise when a with statement is the better tool
Definition
The finally clause of a try statement contains code that runs no matter how the try statement is left: normally, through an exception (handled or not), or via return, break or continue.
Introduction
Files must be closed, locks released and connections returned whether or not the work succeeded. finally is Python's guarantee that cleanup happens.
Why it matters
Leaked resources cause bugs that appear only under load: 'too many open files', stuck locks, exhausted database connections. finally prevents them.
Detailed explanation
Syntax: try: ... finally: ... with or without except and else clauses in between.
The finally block runs after the try (and any except/else) block, whatever happened.
If an exception is not handled, finally runs first and then the exception continues to propagate.
If the try block executes return, finally still runs before the function actually returns.
Avoid return, break or continue inside finally itself: they silently discard any exception in flight (Python 3.14 warns about this).
Typical contents: closing files or connections, releasing locks, restoring a changed setting, printing timing information.
For common resources, a with statement (context manager) does the same job more concisely: with open(path) as f: closes f automatically.
Syntax
- finally always runs.
- Unhandled exceptions continue after it.
- with statements wrap this pattern.
Code examples
finally runs on every path
divide(6, 3) finished 2.0 divide(1, 0) finished None
Cleanup before propagation
cleanup runs first then caught: boom
More examples
Never leaking a connection
open db1 close db1 db1: ok open db1 close db1 error: DROP not allowed open connections: 0
Step-by-step explanation
- The connection is opened before try, so finally only closes something that exists.
- On success, close runs before the return value reaches the caller — which is why 'close db1' prints before 'db1: ok'.
- On failure, close runs and then the PermissionError propagates; the counter returns to zero either way.
Expected output
Running “Never leaking a connection” prints exactly:
Practical applications
- Releasing a threading.Lock.
- Restoring the working directory after temporarily changing it.
Best practices
- Use finally (or with) for every acquired resource.
- Acquire the resource just before try.
- Keep finally blocks short and safe.
Common mistakes
Acquiring the resource inside try
Avoid
Prefer
If acquisition fails there is nothing to clean up, and f doesn't exist.
return inside finally
Avoid
Prefer
A return in finally hides any exception that was propagating.
Important notes
- File Handling covers with statements and context managers in depth.
Key takeaways
- finally always runs.
- It runs before a return completes and before an exception propagates.
- Prefer with statements for standard resources.
Try it yourself
- 1Write a timer that prints how long a block took in finally, even when it fails.
- 2Predict the output of a function with print statements in try, except and finally for both success and failure.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
2 questions test this exact topic. Answers and explanations are revealed after you submit.
- ModerateWhat is printed?
- ModerateWhat is printed?