Exception Best Practices
Follow these guidelines for clean exception handling: catch specific types, never swallow exceptions silently, use context managers, and prefer EAFP (Easier to Ask Forgiveness than Permission) over LBYL.
Follow these guidelines for clean exception handling: catch specific types, never swallow exceptions silently, use context managers, and prefer EAFP (Easier to Ask Forgiveness than Permission) over LBYL.
# EAFP style (Pythonic)
try:
value = data["key"]
except KeyError:
value = default
# LBYL style (less Pythonic)
if "key" in data:
value = data["key"]
else:
value = default
EAFP is generally preferred in Python because it is cleaner and faster.