finally Finally clause
Last updated: 2026-09-22
finally Finally clause
finally always runs whether an exception occurred or not.
| Category | Keywords & Statements |
|---|---|
| Kind | Keyword / Statement |
| Python Version | all |
📝 Syntax
try:
block
finally:
cleanup
▶ Example
Edit the code, press Run, and see the result in the output panel:
Output:
try
cleanup
🏷️ Related Keywords / Statements
💡 Related Cases
More case studies coming soon — check back later.
❓ FAQ
QDoes the code in `finally` always execute?
AAlmost always. Even if `try` has a `return` or raises an exception, `finally` runs before exiting. The only exceptions are extreme cases like the process being force-killed, a power loss, or an interpreter crash.
QWhat happens if you write `return` inside `finally`?
AA `return` in `finally` overrides the value returned by the `try` block — a classic trap. Do not `return` or raise an exception in `finally`; it should only do cleanup.
QBoth `finally` and `with` can clean up resources. How do you choose?
AFor managing resources like files, locks, and connections, prefer `with` (cleaner, officially recommended). Use `finally` for any cleanup logic that must run as a fallback, e.g. `finally: conn.close()`.