🐍 Introduction to Python finally Block
In Python, the finally block is like that one friend who always shows up — no matter what happens. Whether an exception is raised or not, the code inside finally will always run.
It’s most commonly used for clean-up actions, like closing files, releasing resources, or saying “I’m done!” 🧹
🧠 Why Use finally?
- It runs no matter what — whether there’s an error or not.
- Ensures critical operations are always completed (e.g., closing a file or DB connection).
- Makes your programs more robust and predictable.
🔧 Example: try, except, and finally in Action
Let’s say you’re trying to divide two numbers, but one of them could be zero (oh no!). Here’s how finally saves the day:
try:
print("Trying to divide...")
result = 10 / 0
except ZeroDivisionError:
print("Oops! You can't divide by zero.")
finally:
print("This will always run, even if there's an error.")
🎓 Real-Life Analogy
Imagine cooking instant noodles:
try: Boil water 🍲except: Realize there’s no gas and call for help 🔥finally: Clean up the kitchen anyway 🧼
See? No matter what — you clean up!
📦 Another Example: File Handling
Here’s a practical example where finally ensures a file is closed:
try:
file = open("example.txt", "r")
data = file.read()
print(data)
except FileNotFoundError:
print("File not found.")
finally:
print("Closing the file.")
file.close()
✅ Key Takeaways
finallyalways runs — error or no error.- Use it for clean-up actions: closing files, freeing memory, etc.
- Makes your code safe and professional.
🧪 Practice Time!
Try writing a program that connects to a pretend server, throws an error, and always logs out in the finally block.