Sub topic 14
Best practices: narrow handlers, EAFP, and what to avoid
This chapter assumes you can write try/except/else/finally statements, know the built-in exception hierarchy, and have defined a simple custom exception class. It collects the habits that keep error handling reliable.
Keep handlers narrow
A handler should name the exceptions you expect and know how to deal with. Two forms are almost always mistakes:
- A bare
except:catchesBaseException, includingKeyboardInterruptandSystemExit. Ctrl+C stops working inside it. except Exception:that does nothing hides real bugs, such as a typo that raisesNameError.
Keep the try block small too. Put only the risky call inside it, and move the rest into else.
def read_count(path):
try:
f = open(path)
except FileNotFoundError:
return 0
else:
with f:
return int(f.read())Here, only open is guarded. A ValueError from int() on a corrupt file is not caught, so it surfaces instead of being reported as "file missing".
EAFP versus LBYL
Python style prefers EAFP: "easier to ask forgiveness than permission". You try the operation and handle the failure. The alternative is LBYL, "look before you leap", where you check conditions first.
settings = {"retries": "3"}
# LBYL: check, then act
if "retries" in settings and settings["retries"].isdigit():
retries = int(settings["retries"])
else:
retries = 1
# EAFP: act, then handle failure
try:
retries = int(settings["retries"])
except (KeyError, ValueError):
retries = 1
print(retries)EAFP avoids a race condition when the state can change between the check and the use. A file may exist when you call os.path.exists and be deleted before you call open. It also keeps the normal path short. Use LBYL when the check is cheap and the failure would have side effects, or when an exception would be too slow because failure is the common case.
Handle or propagate, not both
Catch an exception only where you can do something useful: recover, retry, add context, or translate it. Otherwise let it propagate. If you log and re-raise, do so once, near the boundary of your program, or you get the same error logged at every level.
Checklist of things to avoid
| Avoid | Why | Do instead |
|---|---|---|
| Bare `except:` | Catches `KeyboardInterrupt` and `SystemExit` | Name the exception types |
| `except Exception: pass` | Hides bugs silently | Handle it, or log and re-raise |
| Large `try` blocks | Catches errors from unrelated lines | Guard only the risky call |
| Replacing the original error | Loses the root cause | Use `raise NewError(...) from exc` |
| Manual `try/finally` cleanup | Easy to get wrong | Use a `with` statement |
| Exceptions for normal flow with a hot loop | Slower when failure is common | Check first (LBYL) |
Choosing an approach
Common errors
- Catching an exception and returning
None. Callers then fail later with a confusingAttributeErrororTypeError. - Listing a broad class before a narrow one. The narrow handler is never reached.
- Using exceptions as messages. Put useful values in the message, such as
f"invalid port: {raw!r}".
Exercise
The function below should return 0 when the file is missing, but it also returns 0 when the file contains text such as "abc". Fix it so only a missing file returns 0. def read_count(path): try: with open(path) as f: return int(f.read()) except Exception: return 0
Show answer
Narrow the handler and shrink the try block so the ValueError from int() is not caught: def read_count(path): try: f = open(path) except FileNotFoundError: return 0 with f: return int(f.read()) Now a corrupt file raises ValueError, which is a real bug the caller should see.
Exercise
Why is checking os.path.exists(path) before open(path) a weaker choice than wrapping open(path) in try/except FileNotFoundError?
Show answer
The file can be deleted or created between the check and the open call (a race condition), so the check does not guarantee success. The try/except handles the failure at the moment it actually happens.