Finally
Python · Exception Handling
Theory
The finally block runs no matter how the try statement ends: after a successful try, after an except handled an error, when an exception was not caught at all, and even when the try or except executes return, break or continue. That makes it the right place for cleanup that must always happen.
In the example, 10 / 0 is caught and prints 'Error', then finally prints 'Cleanup complete'. If the error had not been caught, finally would still run first and then the exception would continue to the caller. Typical cleanup includes closing files or database connections, releasing locks and deleting temporary files. For files and many connections, the with statement provides the same guarantee automatically, which is why you see with more often than finally in modern code.
Why we use it
Resources like files, connections and locks must be released even when something fails, or they leak and cause problems later. finally guarantees the cleanup code runs on every path.
When to use it
Use finally for cleanup that must always happen, especially for resources without a context manager. When a with statement is available (files, many DB connections), prefer it - it does the same job more neatly.
How it works
- Run the try block
- Did an exception occur? Yes: Look for a matching except. No: Skip the except blocks.
- Was the exception handled? Yes: Run except, then finally. No: Run finally, then it propagates.
- Run finally (always)
- Continue, or propagate the unhandled error
Syntax
try:
...
finally:
cleanup()Example
try:
result = 10 / 0
except ZeroDivisionError:
print("Error")
finally:
print("Cleanup complete")Key points
- Runs even if the exception is not caught, right before it propagates
- Commonly used to close files/connections regardless of outcome
- Also runs when try or except executes return
- A return inside finally overrides other returns - avoid it
- with statements give the same guarantee for files