Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Defining Clean Up Actions in Python
There are numerous situations where we want our program to perform specific cleanup tasks, regardless of whether it runs successfully or encounters an error. While we commonly use try and except blocks to handle exceptions, Python provides a special clause for defining cleanup actions.
The finally clause in a try statement is designed for defining cleanup actions that must be executed under any circumstances ?
Basic Syntax
try:
raise SyntaxError("Sample error")
finally:
print("Learning Python!")
Learning Python! Traceback (most recent call last): File "<stdin>", line 2, in <module> SyntaxError: Sample error
The finally clause executes no matter what, while the else clause executes only when no exception occurs.
Example 1: Successful File Operation
When everything works correctly and no exceptions occur ?
try:
file = open('test.txt', 'w')
file.write("Testing 1 2 3.")
print("Writing to file.")
except IOError:
print("Could not write to file.")
else:
print("Write successful.")
finally:
if 'file' in locals():
file.close()
print("File closed.")
Writing to file. Write successful. File closed.
Example 2: Handling File Exceptions
When an exception occurs during file operations ?
try:
file = open('readonly.txt', 'r')
file.write("Testing 1 2 3.")
print("Writing to file.")
except IOError:
print("Could not write to file.")
else:
print("Write successful.")
finally:
if 'file' in locals():
file.close()
print("File closed.")
Could not write to file. File closed.
Example 3: Unhandled Exceptions
When an error occurs that isn't caught by the except clause, the finally block still executes before the error propagates ?
try:
file = open('test.txt', 'w')
file.write(123) # This will cause TypeError
print("Writing to file.")
except IOError:
print("Could not write to file.")
else:
print("Write successful.")
finally:
if 'file' in locals():
file.close()
print("File closed.")
File closed.
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
file.write(123)
TypeError: a bytes-like object is required, not 'int'
Key Points
- The
finallyclause executes whether an exception occurs or not - It's ideal for cleanup operations like closing files, releasing resources, or logging
- Even if an unhandled exception occurs,
finallyruns before the exception propagates - Use
finallyto ensure critical cleanup code always executes
Conclusion
The finally clause provides a reliable way to ensure cleanup actions execute regardless of program flow. It's essential for resource management and maintaining program integrity even when exceptions occur.
