Python › Exception Handling
How does exception performance (raising/catching) compare to normal control flow, and why does Python's EAFP style still encourage using exceptions for routine control flow, unlike some other languages?
AdvancedAnswer
Raising an exception involves stack unwinding and traceback construction, making it measurably slower than a simple conditional check — HOWEVER, Python's 'Easier to Ask Forgiveness than Permission' (EAFP) philosophy still favors try/except for many cases (like dict key lookups) because the COMMON case (no exception) is actually FASTER than a defensive check-first approach, and exceptions only cost extra time on the (hopefully rare) failure path.
# EAFP: fast in the common case, since 'in' checks aren't needed
try:
value = my_dict["key"]
except KeyError:
value = "default"
# LBYL (Look Before You Leap): always pays the cost of the membership check
if "key" in my_dict:
value = my_dict["key"]
else:
value = "default"Real-world example Understanding why Python code idiomatically favors try/except over defensive pre-checks in many common scenarios, unlike Java or C#.