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
Selected Reading
Finally keyword in Python
The finally keyword in Python defines a block of code that executes regardless of whether an exception occurs or not. This makes it useful for cleanup operations like closing files, database connections, or releasing resources.
Syntax
try:
# Main Python code
except ExceptionType:
# Optional block to handle specific exceptions
finally:
# Code that always executes
Example with Exception Handling
Here's an example where a NameError occurs when trying to print an undefined variable ?
try:
var1 = 'Tutorials'
# NameError is raised
print(var2)
# Handle the exception
except NameError:
print("Variable is not found in local or global scope.")
finally:
# Regardless of exception generation,
# this block is always executed
print('Finally block code here')
Variable is not found in local or global scope. Finally block code here
Example without Exception Handling
Even when no except block is present, the finally block still executes before the program terminates ?
try:
var1 = 'Tutorials'
# NameError is raised
print(var2)
# No exception handling
finally:
# This block always executes
print('Finally block code here')
Finally block code here
Traceback (most recent call last):
File "<string>", line 4, in <module>
print(var2)
NameError: name 'var2' is not defined
Common Use Cases
The finally block is commonly used for cleanup operations ?
def read_file(filename):
file = None
try:
file = open(filename, 'r')
content = file.read()
return content
except FileNotFoundError:
print(f"File {filename} not found")
return None
finally:
if file:
file.close()
print("File closed successfully")
# Test with non-existent file
result = read_file('nonexistent.txt')
File nonexistent.txt not found File closed successfully
Key Points
- The
finallyblock executes whether an exception occurs or not - It runs even when no
exceptblock is present - Perfect for cleanup operations like closing files or database connections
- Executes before the program terminates due to an unhandled exception
Conclusion
The finally block ensures critical cleanup code always runs, making your programs more robust and preventing resource leaks. Use it whenever you need guaranteed execution of cleanup operations.
Advertisements
