Python › Exception Handling

What does the 'finally' block guarantee, and when is it typically used?

Beginner

Answer

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 closed
Real-world example Guaranteeing a file handle or network connection is properly closed regardless of whether processing succeeded or raised.

Common follow-ups: How does the 'with' statement relate to and often replace a manual try/finally for resource cleanup?