Lesson · Exceptions & Defensive Programming
Custom Exceptions
55 min readCustom Exceptions
Custom exceptions give domain failures stable names that are independent of low-level implementation details. A small, intentional hierarchy is usually more useful than dozens of narrowly named classes.
Learning goals
- Define a custom exception class and explain what
class ConfigError(Exception): passactually inherits. - Place a base class where a caller needs one handle for a family of failures and a subclass where one condition differs.
- Attach structured context to an exception, such as the missing key in
MissingConfigError(key), instead of relying on message text. - Decide when an existing built-in type is the better choice than a new class for the same failure.
Mental model
The tree shows the two jobs of the hierarchy: except ConfigError catches every subclass beneath it, so a caller can handle all configuration problems in one place, while except MissingConfigError selects the single condition it can repair. The leaf class names the failure in the caller's vocabulary, and the key that was missing rides on the exception as payload. Keep the tree as wide as the recovery paths actually differ, and no wider.
Mental model
read it top to bottom
Exception
└── ConfigError catch this for the whole family
└── MissingConfigError catch this for one conditionCore idea
A custom exception is a named failure that belongs to the caller's vocabulary rather than the implementation's. One small hierarchy per problem area does the work: a base class marks the family, subclasses mark the conditions a caller can act on differently, and each exception carries the values involved so a distant handler can report specifics. The discipline is to add a class only when something will catch it by name.
Custom exception classes
A custom exception class is a subclass of Exception, or of a closer built-in, that gives a failure from your domain its own name, for example class ConfigError(Exception): pass. Because it is a real class, callers can catch it by name, and the class can carry extra attributes or a custom message. Keep the set small so the hierarchy stays understandable.
Exception inheritance
Exception inheritance lets a handler catch a base class and receive every subclass beneath it, so except ConfigError also catches MissingConfigError. This is how one hierarchy offers a coarse handle for the whole family and precise handles for single conditions. Put shared behavior and the broad contract on the base class; put the specifics in subclasses.
Domain-specific errors
A domain-specific exception names a failure in terms meaningful to the caller, independent of which low-level library detected it. This stabilizes the API across implementation changes.
Useful context
Useful context is data carried on the exception so a handler far from the failure can still explain it: MissingConfigError(key) stores the offending key, and str(exc) includes it in the message. The payload travels with the exception as it unwinds, so the frame that catches can log or report specifics it never had direct access to. Prefer a few named attributes over a long free-form message when callers need to read the fields.
Walkthrough
class ConfigError(Exception)declares the family name for this domain. It inherits all the normal exception machinery, including message and traceback handling, sopassis a complete body.class MissingConfigError(ConfigError)narrows the family to one condition. A caller that catchesConfigErroralso catches this class, becauseexceptmatches subclasses, and that is the mechanism that lets one handler cover the whole family.raise MissingConfigError(key)passes the missing key as the exception argument, so the payload travels with the exception.requireitself does not catch it; a caller usingexcept MissingConfigError as exccan read the key fromexc.args[0].- Predict before running: which
exceptclauses catchrequire({}, "port"), and whatstr()of the raised exception displays.
Experiments to try
- Call
require({"port": 8080}, "port")andrequire({}, "port"). Compare the returned value with the traceback of the failing call. - Catch the same failure three ways, as
MissingConfigError, asConfigError, and asException, printing the class that was caught. Confirm which of the three handlers runs for one raise. - Add a
__str__method toMissingConfigErrorthat returnsf"missing config key: {self.args[0]}"and check how the last line of the traceback changes. - Change
MissingConfigErrorto subclassKeyErrorinstead ofConfigError, then re-run the catch experiment. Note that handlers forKeyErrornow match this type too, while theConfigErrorhandlers from the earlier experiments no longer do, and say why the choice of parent changes existing code.
Common mistakes
- Subclassing
Exceptiondirectly when a built-in parent fits: catchingValueErrorelsewhere no longer covers the new class, so the same condition needs a second name in every handler. Subclass the closest built-in when the failure is a kind of that built-in. - Growing a deep or wide hierarchy: every type has to be documented, tested, and woven into callers'
exceptladders, while two or three classes tied to real recovery paths cover almost every case. - Raising with no message or payload:
raise MissingConfigError()tells a distant handler nothing it cannot guess from the type, and the traceback has no key or value to show. - Catching the base class around unrelated code:
except ConfigErrorwrapped over loading and parsing absorbs programming errors from other lines and mislabels them as configuration problems.
Practice: Easy
- Run both paths of the worked example: a present key returns its value, a missing key raises
MissingConfigError("port"). Record the class, the argument, andstr()of the exception. - Catch the missing-key failure as
ConfigErrorand printtype(exc).__name__andexc.args. Explain both results from the class tree in the mental model. - Give
MissingConfigErroran__init__that storesself.key = keyafter callingsuper().__init__(key), then readexc.keyat the call site.
Practice: Medium
- Add
InvalidConfigError(ConfigError)and arequire_port(config)helper that raises it when the port value is not anint. Write two handlers, one per subclass, and confirm which one each failure reaches. - Write a
load_config(path)function that raisesMissingConfigErrorwhen the path does not exist and lets otherOSErrorfailures propagate. Test it with a real file, a missing path, and a directory path. - Find a place in your own code where a plain
ValueErrormessage carries a specific condition a caller recovers from, and give that condition its own class underValueError. List what callers can now catch by name.
Practice: Hard
- Design a two-level hierarchy for an input-validation module: a base
ValidationErrorplus at least two leaf classes for conditions a caller handles differently. Document each class's payload and the handler that should catch it before writing code. - Build a failure lab around the tree: catch
MissingConfigError,ConfigError, andExceptionin three variants and record which handles each raise. Add a second leaf class and predict which handlers catch it without any changes. - Connect this lesson to exception chaining (lesson 73): wrap a low-level failure from a standard library call in your
ConfigError, and sketch whereraise ConfigError(...) from originalbelongs so the original traceback survives.
Lesson checklist
- I can define a custom exception class and explain what
passas its body still gives me. - I can place a base class where a caller needs a family-wide handle and a subclass where one condition differs.
- I can attach the offending key or value to an exception so a distant handler can report it.
- I can decide when a built-in type is the better choice than a new class for the same failure.
Remember
Custom exceptions give a domain its own failure vocabulary: one base class for the family and leaves for the conditions a caller handles differently. `except` matches subclasses, so the hierarchy lets one handler cover the family while narrow handlers still pick out single conditions, and the exception payload carries the values a distant frame needs. Add a class when something will catch it by name, and subclass the closest built-in when the condition is a kind of that failure.
Interview angles
What is the main purpose of **Custom exception classes**?+
A custom exception class is a subclass of Exception, or of a closer built-in, that names a failure from your domain, for example class ConfigError(Exception): pass. Callers can catch it by name, and it can carry extra attributes; keep the set small.
What should you pay attention to when using **Exception inheritance**?+
Exception inheritance lets a handler catch a base class and receive every subclass beneath it, so except ConfigError also catches MissingConfigError. One hierarchy offers a family-wide handle and precise handles for single conditions.
How does **Domain-specific errors** fit into this lesson?+
A domain-specific exception names a failure in terms meaningful to the caller, independent of which low-level library detected it. This stabilizes the API across implementation changes.
Why subclass `ValueError` (or another built-in) rather than `Exception` when the condition is a kind of that failure?+
Handlers that already catch the built-in, such as except ValueError, keep working for the new class, so the same kind of failure does not need two except names. The subclass still adds a precise name for callers that want it.