🧹 Python finally Block β€” Guaranteed Execution

Introduction 🌟

The finally block in Python is used to run code **no matter what happens** β€” whether an exception occurs or not. It is commonly used for cleanup tasks like closing files, releasing resources, or disconnecting from a server.

Note

πŸ’‘ The finally block ALWAYS executes β€” even if there is a return inside try or except.

1. Basic try–except–finally Structure 🧱

basic_finally.py

try:
    print("Trying to divide...")
    x = 10 / 0
except ZeroDivisionError:
    print("❌ Cannot divide by zero!")
finally:
    print("πŸŽ‰ This will ALWAYS run!")

βœ” finally runs even though an error occurred.

2. finally Without except πŸ”

try_finally.py

try:
    print("Opening file...")
finally:
    print("Closing file...")

βœ” Valid usage when you only need try and finally.

3. finally Executes Even If No Error Occurs βœ”οΈ

finally_no_error.py

try:
    print("No error here!")
except:
    print("This won't run")
finally:
    print("πŸŽ‰ Finally still runs")

4. finally Executes Even With return Statement πŸ”

Note

⚠️ Important rule: finally runs BEFORE the function returns

finally_with_return.py

def test():
    try:
        return "Returning from try"
    finally:
        print("Running finally block...")

print(test())

βœ” Output:
Running finally block...
Returning from try

5. finally Executes Even With break or continue πŸ”‚

finally_loop.py

for i in range(3):
    try:
        if i == 1:
            break
    finally:
        print("Cleaning up for i =", i)

βœ” finally still executes before loop breaks.

6. Real-World Use Case: File Handling πŸ“

file_finally.py

try:
    f = open("data.txt")
    print(f.read())
except FileNotFoundError:
    print("❌ File not found!")
finally:
    print("Closing file...")
    # f.close()

Note

βœ” Use finally to ensure resources are always cleaned up.

7. Real-World Use Case: Database Connection πŸ”Œ

db_finally.py

try:
    print("Connecting to database...")
    raise Exception("DB error")
except Exception as e:
    print("❌ Error:", e)
finally:
    print("Disconnecting from database...")

8. try–except–else–finally Together 🎯

full_structure.py

try:
    num = int("10")
except ValueError:
    print("❌ Invalid number!")
else:
    print("βœ” No errors! Converted:", num)
finally:
    print("πŸŽ‰ Execution finished")

9. When to Use finally? 🧠

  • βœ” Closing files
  • βœ” Releasing database connections
  • βœ” Stopping threads or timers
  • βœ” Logging completion messages
  • βœ” Ensuring cleanup after exceptions

10. Common Mistakes ⚠️

  • ❌ Writing important logic in finally that depends on try success
  • ❌ Forgetting that finally overrides return if it also returns

bad_finally.py

def bad():
    try:
        return 10
    finally:
        return 20   # Overrides previous return!

print(bad())  # 20

Note

⚠️ Avoid returning values from finally.

Conclusion πŸŽ‰

>>β€œThe finally block guarantees cleanup β€” no matter what happens, your program remains stable.” ✨

You now fully understand the Finally Block in Python! Want the next topic? Try Custom Exceptions, Raising Exceptions, Else Block, or Error Hierarchies. Just tell me! 😊