Junior — Middle
Explain how the finally block works together with try and except in Python and what it is used for.
sobes.tech AI
Answer from AI
In Python, the finally block is used together with try and except to ensure that certain code is executed regardless of whether an exception occurs or not. This is useful for releasing resources, closing files, releasing locks, and other cleanup operations.
Workflow:
- The main code is executed in the
tryblock. - If an exception occurs, control is transferred to the corresponding
exceptblock. - After executing
tryand/orexcept, thefinallyblock is always executed.
Example:
try:
f = open('file.txt')
data = f.read()
except IOError:
print('Error reading file')
finally:
f.close() # guarantees the file is closed
Thus, finally ensures the execution of critical cleanup code regardless of errors.