Skip to main content
Albero Academy

finally & Cleanup

Guarantee cleanup runs whether or not an error occurred.

Exceptions7 min

A finally block runs no matter what — whether the try succeeded, raised an exception, or even returned early. It's the place for cleanup that must always happen: closing files, releasing locks, rolling back transactions.

Guaranteed cleanup

finally always runs
f = open("data.txt")
try:
process(f) # might raise
except IOError:
print("read failed")
finally:
f.close() # runs on success AND on error

Prefer a context manager

For common resources, a with block does this cleanup automatically — it's shorter and impossible to forget. Reach for finally directly only when there's no context manager for what you're cleaning up:

the with equivalent
with open("data.txt") as f:
process(f)
# f is closed automatically here — even if process() raised

Key takeaways

  1. 01finally always runs — after success, an exception, or a return.
  2. 02Use it to release resources: files, locks, connections.
  3. 03A with block automates this for common resources — prefer it.
  4. 04Avoid returning from finally; it can silently swallow exceptions.

Finished this chapter?

Mark it complete to track your progress through Python.