In Python, sometimes you need to make sure a piece of code always runs, no matter what happens in your program. For this purpose, Python provides the try-finally block.
This is commonly used for clean-up actions like closing files, releasing resources, or ending connections properly.
🔹 What is Try–Finally in Python?
The try-finally block ensures that:
The
finallyblock always executes, even if an error occurs in thetryblock.
It does NOT handle errors—it only guarantees execution.
🔹 Syntax of Try–Finally Block
try:
# risky code
finally:
# always executed code
🔹 How Try–Finally Works
-
Python executes the
tryblock -
If error occurs → program still continues to
finally -
If no error →
finallystill runs -
After
finally, error is raised (if not handled elsewhere)
🔹 Simple Example of Try–Finally
try:
print("Inside try block")
finally:
print("This will always execute")
🔸 Output:
Inside try block
This will always execute
🔹 Example With Error
try:
print(10 / 0)
finally:
print("Finally block executed")
🔸 Output:
Finally block executed
ZeroDivisionError: division by zero
🔍 Explanation:
-
Error occurs in
try -
Still,
finallyruns before program stops
🔹 Try–Finally with File Handling
One of the most important uses of finally is closing files.
file = None
try:
file = open("data.txt", "r")
content = file.read()
print(content)
finally:
if file:
file.close()
print("File closed successfully")
🔍 Why this is important:
- Even if reading fails, file will still be closed
- Prevents memory leaks and resource issues
🔹 Real-Life Analogy
Think of try-finally like this:
You try to open a door (try), but whether it opens or not, you must lock it again when leaving (finally).
🔹 Try–Except vs Try–Finally
| Feature | try-except | try-finally |
|---|---|---|
| Handles errors | ✅ Yes | ❌ No |
| Ensures cleanup | ❌ Not always | ✅ Always |
| Prevents crash | ✅ Yes | ❌ No |
🔹 Using Try–Finally Without Except
You can use try-finally without except, but errors will still crash the program after finally.
try:
print("Running risky code")
x = 10 / 0
finally:
print("Cleanup done")
🔹 Best Use Cases of Finally Block
✔ Closing files
✔ Releasing database connections
✔ Cleaning temporary resources
✔ Ending network connections
✔ Resetting states
🔹 Example: Database Connection Style (Concept)
try:
print("Connecting to database...")
print("Running query...")
finally:
print("Closing database connection")
🔹 Key Points to Remember
-
finallyALWAYS executes - Works even if error occurs
- Does NOT handle exceptions
- Mostly used for cleanup operations
-
Can be used alone or with
try-except
🚀 Conclusion
The Python try-finally block is essential for writing safe and reliable programs. It ensures that important cleanup code is always executed, even when errors occur.
If you are working with files, databases, or network connections, finally is a must-use feature to prevent resource leaks.


0 Comments