How to Use finally in Python: Syntax and Examples
In Python, the
finally block is used after try and except blocks to run code that must execute no matter what, such as cleanup actions. The code inside finally always runs whether an exception occurs or not.Syntax
The finally block follows try and optional except blocks. It contains code that always runs after the try block finishes, whether an exception was raised or handled.
- try: Code that might cause an error.
- except: Code to handle errors.
- finally: Code that runs no matter what.
python
try: # code that may raise an exception pass except SomeError: # code to handle the exception pass finally: # code that always runs pass
Example
This example shows how finally runs even if an error happens or not. It prints messages to show the flow.
python
try: print("Trying to open a file...") file = open("nonexistent.txt", "r") except FileNotFoundError: print("File not found error caught.") finally: print("This runs no matter what.")
Output
Trying to open a file...
File not found error caught.
This runs no matter what.
Common Pitfalls
One common mistake is to think finally only runs if there is an exception. It runs always, even if no error occurs. Another pitfall is placing return statements inside try or except blocks and expecting finally to not run; it still runs before the function returns.
python
def test_finally(): try: return "From try" finally: print("Finally block runs before return") result = test_finally() print(result)
Output
Finally block runs before return
From try
Quick Reference
| Keyword | Purpose |
|---|---|
| try | Run code that might cause an error |
| except | Handle specific errors |
| finally | Run code no matter what, for cleanup |
Key Takeaways
The finally block always runs after try and except blocks, regardless of errors.
Use finally for cleanup actions like closing files or releasing resources.
Finally runs even if there is a return statement in try or except blocks.
Don’t assume finally only runs on exceptions; it runs every time.
Place critical cleanup code inside finally to ensure it executes.