Sobes.tech
Junior — Middle

Explain the purpose and operation of the finally block in try-catch exception handling.

sobes.tech AI

Answer from AI

The finally block in Python is used in the try-except-finally construct and guarantees the execution of the code inside it regardless of whether an exception was raised or not.

This is useful for releasing resources, closing files, releasing locks, and other actions that must be performed to avoid leaks or deadlocks.

Example:

try:
    file = open('data.txt', 'r')
    data = file.read()
except IOError:
    print('Error reading file')
finally:
    file.close()  # This code will always execute

In this example, the file will be closed in any case — even if an error occurs during reading.