Advertisement
Beginner Python, Exception Handling

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

Short 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.

Save Python mock interview
Advertisement
AModel 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.
Likely follow-ups
  • How does the 'with' statement relate to and often replace a manual try/finally for resource cleanup?
Related topics