Skip to content

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.

Beginner 8 min read·Lesson 189 of 306 in Python Programming

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

Python
conn = connect()
try:
conn.query(sql)
finally:
conn.close() # always runs
  • finally always runs.
  • Unhandled exceptions continue after it.
  • with statements wrap this pattern.

Code examples

finally runs on every path

Python
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
return None
finally:
print(f"divide({a}, {b}) finished")
print(divide(6, 3))
print(divide(1, 0))
Output
divide(6, 3) finished
2.0
divide(1, 0) finished
None

Cleanup before propagation

Python
def risky():
try:
raise ValueError("boom")
finally:
print("cleanup runs first")
try:
risky()
except ValueError as e:
print("then caught:", e)
Output
cleanup runs first
then caught: boom

More examples

Never leaking a connection

Python
class Connection:
open_count = 0
def __init__(self, name):
self.name = name
Connection.open_count += 1
print(f"open {name}")
def query(self, sql):
if "DROP" in sql:
raise PermissionError("DROP not allowed")
return f"{self.name}: ok"
def close(self):
Connection.open_count -= 1
print(f"close {self.name}")
def run(sql):
conn = Connection("db1")
try:
return conn.query(sql)
finally:
conn.close()
print(run("SELECT 1"))
try:
run("DROP TABLE users")
except PermissionError as e:
print("error:", e)
print("open connections:", Connection.open_count)
Output
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:

TextOutput
open db1
close db1
db1: ok
open db1
close db1
error: DROP not allowed
open connections: 0

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

try:
f = open(path)
...
finally:
f.close() # NameError if open failed

Prefer

f = open(path)
try:
...
finally:
f.close()

If acquisition fails there is nothing to clean up, and f doesn't exist.

return inside finally

Avoid

finally:
return result

Prefer

finally:
cleanup()

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

  1. 1
    Write a timer that prints how long a block took in finally, even when it fails.
  2. 2
    Predict 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?
Practise this topic