Python finally statement
Created By: chatGPT
Finally statements in Python are used in conjunction with try and except blocks. The code within the finally block will execute after the try block completes, regardless of whether an exception was raised or not. This is particularly useful for cleaning up resources, such as closing files or releasing network connections, that must occur regardless of the success of the try block. Here's an example to illustrate its usage.
try:
file = open('example.txt', 'r')
data = file.read()
print(data)
except FileNotFoundError:
print('File not found!')
finally:
if 'file' in locals():
file.close()
print('File closed.')
In the above code:
- The try block attempts to open and read a file named 'example.txt'.
- If the file does not exist, a FileNotFoundError is caught in the except block, and a message is printed.
- Regardless of whether an exception occurred, the finally block checks if the file variable exists in the local scope and closes it. This ensures that resources are properly managed.
try:
# Open and read file
with open('example.txt', 'r') as file:
data = file.read()
print(data)
except FileNotFoundError:
print('File not found!')
finally:
print('Executing finally block.')
This example simplifies the previous one by using the with statement, which automatically handles closing the file for you. However, the finally block is still included to demonstrate its purpose. It will execute regardless of the result of the try block, ensuring that any final actions you wish to perform are carried out.
def divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print('Cannot divide by zero!')
finally:
print('Division operation attempted.')
return result if 'result' in locals() else None