Error-Checking Strategies
Most programming languages that support exceptions are geared to raise exceptions only in rare cases. Python’s emphasis is different. In Python, exceptions are considered appropriate whenever they make a program simpler and more robust, even if that means that exceptions are raised rather frequently.
LBYL Versus EAFP
A common idiom in other languages, sometimes known as “look before you leap” (LBYL), is to check in advance, before attempting an operation, for all circumstances that might make the operation invalid. This approach is not ideal for several reasons:
The checks may diminish the readability and clarity of the common, mainstream cases where everything is okay.
The work needed for checking may duplicate a substantial part of the work done in the operation itself.
The programmer might easily err by omitting some needed check.
The situation might change between the moment the checks are performed and the moment the operation is attempted.
The preferred idiom in Python is generally to attempt the operation in a try clause and handle the exceptions that may result in except clauses. This idiom is known as “it’s easier to ask forgiveness than permission” (EAFP), a motto widely credited to Admiral Grace Murray Hopper, co-inventor of COBOL, and that shares none of the defects of LBYL. Here is a function written using the LBYL idiom:
def safe_divide_1(x, y):
if y==0:
print "Divide-by-0 attempt detected"
return None
else:
return x/yWith LBYL, the checks come first, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access