As it is indicated in the documentation, the finally
clause is useful for releasing external resources, regardless of whether the use was successful. These external resources can be files or network connections, which require to be cleaned-up under all circumstances.
For instance:
try:
f = open("testfile", "w")
try:
f.write("This may not work!")
finally:
f.close()
except IOError:
print("Error! Can't find file")
The statement f.close()
will always be executed, so even if the write operation raises an exception, the file will always be closed at the end.