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
f = open("data.txt")try:process(f) # might raiseexcept 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:
with open("data.txt") as f:process(f)# f is closed automatically here — even if process() raised
Key takeaways
- 01finally always runs — after success, an exception, or a return.
- 02Use it to release resources: files, locks, connections.
- 03A with block automates this for common resources — prefer it.
- 04Avoid returning from finally; it can silently swallow exceptions.
