Else and Finally Clauses
The else block runs when no exception occurs. The finally block always runs — ideal for cleanup like closing files.
The else block runs when no exception occurs. The finally block always runs — ideal for cleanup like closing files.
try:
f = open("data.txt")
except FileNotFoundError:
print("File not found")
else:
content = f.read()
print(content)
finally:
print("Done")
Use finally to release resources whether or not an error occurred.