π§― Try / Except / Finally¶
The try statement lets you separate normal logic from error handling. You can catch errors, run cleanup code, or execute alternative paths safely.
β Basic Pattern¶
β
else and finally¶
elseruns only if no exception happened.finallyruns always (success or failure), perfect for cleanup.
try:
file = open("data.txt")
data = file.read()
except FileNotFoundError:
data = ""
else:
print("Read successful")
finally:
file.close()
β Catching Multiple Exceptions¶
try:
result = data["count"] / total
except (KeyError, ZeroDivisionError) as exc:
print("Problem:", exc)
β οΈ Donβt Catch Too Broadly¶
Prefer catching specific errors you expect.
π Key Takeaways¶
- Use
try/exceptto handle known failure cases. - Use
elsefor success-only logic. - Use
finallyfor cleanup and releasing resources.