Junior — Middle
What is the purpose of the finally block in a try...except construct in Python?
sobes.tech AI
Answer from AI
In Python, the finally block is used in the try...except...finally construct to execute code that must run regardless of whether an exception occurred or not.
Purpose of finally:
- Releasing resources (e.g., closing files, network connections)
- Performing cleanup actions
Example:
try:
f = open('file.txt', 'r')
data = f.read()
except IOError:
print('Error reading file')
finally:
f.close() # Close the file in any case
In this example, the file will be closed even if an error occurs during reading, preventing resource leaks.