The finally Block
Sometimes, your program opens important resources — like a file, a database connection, or a network socket. If an error occurs in the middle of using that resource, the program crashes and the resource is never properly closed.
The finally block guarantees that cleanup code always runs, no matter what happens — whether the try block succeeds, an exception is caught, or even if an unhandled error occurs.
The Real-World Analogy: Restaurant Closing Duties
Imagine you work at a restaurant. At the end of the night, you must:
- Lock the doors
- Turn off the lights
- Clean the kitchen
You do these things regardless of whether the day was good (lots of customers) or bad (a kitchen fire happened). The closing duties always run.
In Python, the finally block is your closing duties.
How try-except-finally Works
try:
# Step 1: Risky code
print("Opening database...")
result = 10 / 0 # This will crash
except ZeroDivisionError:
# Step 2: Handle the error
print("Cannot divide by zero!")
finally:
# Step 3: Always runs (cleanup)
print("Closing database connection...")
Output:
Opening database...
Cannot divide by zero!
Closing database connection...
When Does finally Run?
| Scenario | Does finally run? |
|---|---|
try block succeeds (no error) | ✅ Yes |
except catches an error | ✅ Yes |
| An error occurs but is NOT caught | ✅ Yes (runs before crash) |
return statement inside try or except | ✅ Yes (runs before returning) |
Practical Example: Safe File Reader
file = None
try:
file = open("config.txt", "r")
data = file.read()
print(data)
except FileNotFoundError:
print("Error: config.txt not found!")
finally:
if file:
file.close()
print("File handle closed safely.")
Even if the file does not exist and FileNotFoundError fires, the finally block ensures we attempt to close the file handle properly.
Use the finally block for cleanup tasks — closing files, releasing database connections, or stopping timers. This prevents resource leaks that can slow down or crash long-running applications.
Quick Summary
- Guaranteed Execution: The
finallyblock always executes, regardless of whether exceptions were raised, caught, or missed. - Resource Cleanup: Ideal for closing network sockets, releasing database connections, or freeing file handles.
- Safety Pattern: Prevents resource leaks that could freeze servers or crash production software.
What's Next?
Let's look at how to cleanly separate success logic from risky operations using the else block in the next lesson!