Python › Exception Handling
What does the 'finally' block guarantee, and when is it typically used?
BeginnerAnswer
Code in 'finally' ALWAYS runs after try (and any except) completes, whether an exception occurred or not, and even if the try block contains a 'return' — making it the standard place for cleanup code like closing a file or releasing a lock.
file = open("data.txt")
try:
process(file)
finally:
file.close() # always runs, guaranteeing the file is closedReal-world example Guaranteeing a file handle or network connection is properly closed regardless of whether processing succeeded or raised.