Sub topic 14
Best practices: narrow handlers, EAFP, and what to avoid
This chapter assumes you can write try, except, else, and finally blocks and that you know the exception hierarchy. It also assumes you have seen raise, raise from, and custom exception classes. Here we turn those pieces into habits that make error handling reliable.
Keep the try block narrow
A try block should hold only the statement that can raise the exception you expect. Everything else belongs outside it, or in else. If the block is wide, an unrelated bug that raises the same exception type gets caught by accident and treated as the expected failure.
def read_port(config):
try:
raw = config["port"]
port = int(raw)
return normalize(port) # a bug in here raising KeyError is hidden
except KeyError:
return 8080If normalize raises KeyError because of its own bug, the handler returns the default port and the bug goes unnoticed. Narrow the block so only the lookup is protected:
def normalize(port):
return port
def read_port(config):
try:
raw = config["port"]
except KeyError:
return 8080
else:
return normalize(int(raw))
print(read_port({"port": "9000"}))
print(read_port({}))Now a KeyError from normalize or from int propagates to the caller with a full traceback. The else clause is the right place for code that depends on the try succeeding.
Catch specific exceptions
Catch the most specific type that describes the failure you can handle. A handler is a claim: "I know what went wrong and what to do about it." except ValueError makes that claim for one family of problems. except Exception makes it for nearly all of them.
| Handler | What it catches | Typical verdict |
|---|---|---|
| `except:` (bare) | Everything, including `KeyboardInterrupt` and `SystemExit` | Avoid |
| `except BaseException:` | The same set as the bare form | Avoid, except in rare top-level code that re-raises |
| `except Exception:` | Almost all errors, not exit signals | Only at boundaries, and log or re-raise |
| `except (KeyError, IndexError):` | Exactly the listed types and subclasses | Preferred |
A bare except: is the worst case. It catches KeyboardInterrupt, so the user's Ctrl+C no longer stops the program. It catches SystemExit, so sys.exit() stops working. It also catches GeneratorExit, which breaks generator cleanup.
Never swallow errors silently
Catching an exception and doing nothing is sometimes correct, but only for a named, expected condition. Python provides contextlib.suppress to make that intent explicit.
from contextlib import suppress
import os
with suppress(FileNotFoundError):
os.remove("old-cache.tmp")This reads clearly: a missing file is fine, and any other error still propagates. Compare that with a broad handler around the same call, which would also hide a PermissionError.
EAFP and LBYL
Python programmers usually follow EAFP: "easier to ask forgiveness than permission." You attempt the operation and handle the failure. The opposite style is LBYL: "look before you leap." You check conditions first.
import os
# LBYL: check, then act
def read_lbyl(path):
if os.path.exists(path):
with open(path) as f:
return f.read()
return ""
# EAFP: act, then handle failure
def read_eafp(path):
try:
with open(path) as f:
return f.read()
except FileNotFoundError:
return ""The LBYL version has a race condition. Another process can delete the file between the exists check and the open call, and the program then crashes with the exact error the check was meant to prevent. The EAFP version has no gap, because the check and the use are one operation. EAFP also tends to be shorter when many things could be wrong, since the interpreter performs the checks for you.
EAFP is not always better. Prefer LBYL when:
- The check is cheap and the failure is common. A
dict.get(key, default)orif key in dis clearer than atryblock that fails half the time. - A failure would have side effects you cannot undo, such as sending a message after a partial write.
- The failing operation is expensive, and a simple check can avoid it.
counts = {"a": 2}
# Clear and cheap: no exception needed
print(counts.get("b", 0))
# EAFP shines when the key is usually present
try:
print(counts["a"])
except KeyError:
print(0)Handle errors where you can act on them
Catch an exception at the level that has enough information to recover, retry, or report to a user. Low-level functions usually cannot decide what a failure means, so they should let the exception propagate. A function that opens a configuration file does not know whether the program should fall back to defaults or quit. The code that calls it does.
A common structure has three layers:
- Low-level code raises specific exceptions and does not catch them.
- Mid-level code translates exceptions into your own types, using
raise ... from, when the original type would leak implementation details. - A single top-level handler logs the error, shows a message to the user, and picks an exit code.
import logging
import sys
logger = logging.getLogger(__name__)
class ConfigError(Exception):
"""Raised when configuration is invalid."""
def load_port(raw):
try:
return int(raw)
except ValueError as exc:
raise ConfigError(f"invalid port: {raw!r}") from exc
def main():
port = load_port("abc")
print(f"listening on {port}")
if __name__ == "__main__":
try:
main()
except ConfigError as err:
logger.error("configuration problem: %s", err)
sys.exit(2)Only the entry point decides to exit. Anything below it stays reusable and testable.
Log once, and keep the traceback
If every layer logs an exception and then re-raises it, one failure produces many log entries and the real cause is buried. Choose one place to log, usually the layer that finally handles the error. If a lower layer must log before re-raising, use logger.exception(...), which records the traceback, and then use a bare raise so the original traceback survives.
Two mistakes destroy information:
raise excinside a handler adds a confusing extra traceback line, while a bareraisere-raises the active exception unchanged.raise NewError(...)withoutfromstill chains implicitly, but the message says "During handling of the above exception, another exception occurred," which suggests a bug in the handler. Usefrom excto state the link on purpose, orfrom Noneto hide the cause when it is only noise.
Do not use exceptions for ordinary control flow
Exceptions suit exceptional or unusual conditions. Python itself uses StopIteration internally, but your own code should not use exceptions to jump out of nested logic when a return value or a loop condition would do. Exception-based flow is harder to read and, when the exception is raised often, slower than a plain check.
Also avoid returning None or -1 to signal an error when the caller is likely to forget to check. An exception cannot be ignored by accident. A sentinel value can.
Always release resources
Use a with statement for files, locks, sockets, and database connections instead of try/finally written by hand. Context managers guarantee cleanup on every path and keep the cleanup next to the acquisition.
from contextlib import contextmanager
@contextmanager
def opened(path):
f = open(path)
try:
yield f
finally:
f.close()
with opened(__file__) as f:
first_line = f.readline()
print(first_line)Do not put return, break, or continue inside finally. As the earlier chapter showed, a return in finally discards a pending exception, and the failure vanishes without a trace.
Write useful messages
An error message is read by someone who is debugging at an inconvenient moment. Include the offending value, using !r so that whitespace and quotes are visible, and state what was expected.
- Weak:
raise ValueError("bad input") - Better:
raise ValueError(f"port must be between 1 and 65535, got {port!r}")
Prefer built-in exception types when they fit: ValueError for a right type with a wrong value, TypeError for a wrong type, KeyError and IndexError for lookups. Define your own class when callers need to catch your errors separately from everything else.
Checklist
- Wrap the smallest possible statement in
try. - Catch named exception types, and order subclasses before their parents.
- Put code that depends on success in
else. - Never use a bare
except:orexcept: pass. - Re-raise with a bare
raise, or translate withraise ... from. - Log once, with the traceback.
- Use
withfor cleanup, and keepreturnout offinally. - Write messages that include the value and the expectation.
Exercise
The function below is meant to return a default of 0 when the text is not a number. Name two problems with it and rewrite it. def to_int(text): try: value = int(text) print("converted", value) return value * 2 except: return 0
Show answer
Problem one: the bare except: also catches KeyboardInterrupt and SystemExit, and it would hide unrelated bugs. Problem two: the try block is too wide, so an error in the later code is treated as a bad input. A fixed version:
def to_int(text):
try:
value = int(text)
except ValueError:
return 0
else:
print("converted", value)
return value * 2
Passing None now raises TypeError to the caller instead of silently returning 0. Add TypeError to the handler only if that case should also yield 0.
Exercise
Why is if os.path.exists(p): open(p) less safe than try: open(p) except FileNotFoundError, and when would you still prefer the check?
Show answer
Between the check and the open call, another process can remove the file, so the check gives no guarantee and the program can still fail. The try version tests and uses the file in a single step. Prefer the check when the failure is common and cheap to detect, or when a failed attempt would cause side effects that cannot be undone.