π§Ή Python
finally Block β Guaranteed ExecutionIntroduction π
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
finallythat depends ontrysuccess - β Forgetting that
finallyoverridesreturnif it also returns
bad_finally.py
def bad():
try:
return 10
finally:
return 20 # Overrides previous return!
print(bad()) # 20Note
β οΈ 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! π