SyntaxStudy
Sign Up
Python Beginner 3 min read

Else and Finally Clauses

Else and Finally Clauses

The else block runs when no exception occurs. The finally block always runs — ideal for cleanup like closing files.

Example
try:
    f = open("data.txt")
except FileNotFoundError:
    print("File not found")
else:
    content = f.read()
    print(content)
finally:
    print("Done")
Pro Tip

Use finally to release resources whether or not an error occurred.