One of the explanations for preferring EAFP (Easier to Ask Forgiveness than Permission) over LBYL (Look Before You Leap) is that LBYL is vulnerable to TOC/TOU race conditions (time-of-check to time-of-use) in concurrent programs. A relatively harmless example in Python:
class Ratio:
def __init__(self, numerator, denominator):
self.n = numerator
self.d = denominator
def LBYL_divide(self):
if self.d != 0: # check
# another thread can change self.d
return self.n/self.d # use
else:
return "NA"
def EAFP_divide(self):
try:
return self.n/self.d
except ZeroDivisionError:
return "NA"
I interpreted examples like these to mean that in EAFP, there's no opportunity for another thread to sneak in between the check and use because they're done on the same line/step. But I'm under the impression that some condition must be checked before an exception is thrown; in this example, / must have checked if self.d != 0 to know to throw a ZeroDivisionError. Why can't another thread sneak in after those checks and cause problems?