Sub topic 12
Defining your own exception classes
This chapter assumes you can use try, except, and raise, and that you know how class inheritance works. It also assumes you know that except clauses match by class, so a handler for a parent class also catches its subclasses.
Why define your own exceptions
Built-in exceptions such as ValueError and KeyError describe low-level problems. They don't say which part of your program failed or what the caller can do about it. A custom exception gives your code a name for a failure that belongs to your domain.
A custom type has three practical benefits:
- Callers can catch exactly your failure with
except RecordNotFoundand leave unrelated bugs alone. - The traceback and log line name the real problem instead of a generic
ValueError. - Your internal choices stay hidden. If you swap a
dictfor a database, callers still catch the same exception.
The minimal custom exception
A custom exception is a class that inherits from Exception. The body can be a docstring alone, because the inherited constructor already accepts a message.
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
try:
load_port("abc")
except ConfigError as err:
print(err)
print(repr(err.__cause__))The output is:
invalid port: 'abc'
ValueError("invalid literal for int() with base 10: 'abc'")raise ... from exc keeps the original ValueError as __cause__. The caller sees a ConfigError and can still reach the low-level detail.
Choosing a base class
Inherit from Exception, not from BaseException. BaseException is the parent of KeyboardInterrupt, SystemExit, and GeneratorExit. A handler written as except Exception is meant to skip those signals. If your class inherits from BaseException, ordinary error handling will not catch it, and a program can exit unexpectedly.
Choose the parent by asking what the failure is:
| Situation | Reasonable parent |
|---|---|
| A failure specific to your domain | `Exception`, or your own base class |
| A bad value that callers may already handle as `ValueError` | `ValueError` |
| A lookup that fails and should behave like a missing key | `LookupError` or `KeyError` |
| A failure related to the operating system | `OSError` |
Inheriting from a built-in subclass is a compatibility promise. Code that catches ValueError will also catch your exception. Make that promise only when it is true.
Build a hierarchy with one base class
For a library or a larger application, define one base exception and derive the specific ones from it. The base class lets callers catch every failure from your package with a single clause. The subclasses let them react to individual cases.
The following code implements this hierarchy:
class StorageError(Exception):
"""Base class for all errors raised by the storage package."""
class RecordNotFound(StorageError):
def __init__(self, key):
super().__init__(f"no record with key {key!r}")
self.key = key
class RecordLocked(StorageError):
def __init__(self, key, owner):
super().__init__(f"record {key!r} is locked by {owner}")
self.key = key
self.owner = owner
_records = {"a": "alpha"}
_locks = {"b": "worker-2"}
def fetch(key):
if key in _locks:
raise RecordLocked(key, _locks[key])
try:
return _records[key]
except KeyError:
raise RecordNotFound(key) from None
for key in ("a", "b", "c"):
try:
print(fetch(key))
except RecordLocked as err:
print(f"retry later, owner is {err.owner}")
except StorageError as err:
print(f"storage failure: {err}")The output is:
alpha
retry later, owner is worker-2
storage failure: no record with key 'c'Three details in this example matter:
- The handler for
RecordLockedcomes before the handler forStorageError. Handlers are tried in order, so the specific class must come first. raise RecordNotFound(key) from Nonehides theKeyError. Use it when the original error is an implementation detail that would only confuse the reader. When the original error helps with debugging, usefrom excinstead.- Each exception stores the data that a handler might need, as attributes (
key,owner). Callers should never have to parse the message text to get them.
Carrying structured data
A message string is for people. Attributes are for code. Put anything a handler might act on into attributes, and build the message from them.
Call super().__init__() in your own __init__. Without that call, args stays empty and the default str(err) returns an empty string. Python's own exception machinery also relies on args. Copying and pickling an exception rebuild it by calling the class with args. This matters when exceptions cross process boundaries, as they do with multiprocessing or concurrent.futures.ProcessPoolExecutor.
Keep the constructor simple. An exception that raises its own error while being created hides the original problem.
Combining a domain base with a built-in
Sometimes an exception should belong to your hierarchy and also be catchable as a built-in type. Multiple inheritance supports both.
class ConfigError(Exception):
"""Base class for configuration problems."""
class InvalidPortError(ConfigError, ValueError):
"""The port is not a valid number in range."""
try:
raise InvalidPortError("port out of range: 70000")
except ValueError as err:
print(type(err).__name__, err)The output is InvalidPortError port out of range: 70000. Code that catches ValueError still works, and code that catches ConfigError also works. This pattern is safe when the built-in parents have compatible internal layouts. Combining two built-ins with different layouts, such as OSError with ValueError, can raise TypeError: multiple bases have instance lay-out conflict. Combine your own base with one built-in, as shown here.
Naming and documentation
- End the class name with
Errorwhen it signals a failure, for exampleConfigErrororRecordNotFoundError. Follow the convention already used in your project. - Name the problem, not the place where it happens.
RecordLockedis more useful thanStorageModuleException. - Write a docstring that states when the exception is raised. Callers read it to decide whether to catch it.
- Put exceptions in one module, often
errors.pyorexceptions.py, so users can import them without importing your whole package.
How many classes are enough
Don't create a class for every message. Add a new exception type only when a caller might handle it differently from the others. If no caller will ever write except YourSpecificError, a descriptive message on an existing type is enough. Start with one base class for the package, and add subclasses when real callers need to tell failures apart. Adding a subclass later is a compatible change, because existing handlers for the base class still catch it.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Inheriting from `BaseException` | `except Exception` no longer catches it | Inherit from `Exception` |
| Skipping `super().__init__()` while defining `__init__` | `args` is empty, `str(err)` is blank, and pickling can fail | Always call `super().__init__(...)` |
| Catching your base class before a subclass | The specific handler never runs | Order handlers from specific to general |
| Parsing `str(err)` in callers | Callers break when the wording changes | Store data in attributes |
| One exception type for every failure | Callers can't react to individual cases | Split types only where handling differs |
Exercise
A package defines class PaymentError(Exception) and class CardDeclined(PaymentError), where CardDeclined.__init__(self, card_last4) stores self.card_last4. Write a charge(card_last4) function that raises CardDeclined when card_last4 == "0000", and a caller that prints "ask for another card" for CardDeclined and "payment problem: <message>" for any other PaymentError. Explain why the order of the two except clauses matters.
Show answer
The code is:
class PaymentError(Exception):
"""Base class for payment failures."""
class CardDeclined(PaymentError):
def _init(self, cardlast4):
super()._init(f"card ending {cardlast4} was declined")
self.cardlast4 = cardlast4
def charge(cardlast4):
if cardlast4 == "0000":
raise CardDeclined(card_last4)
return "ok"
try:
charge("0000")
except CardDeclined:
print("ask for another card")
except PaymentError as err:
print(f"payment problem: {err}")
The CardDeclined clause must come first. Python tries handlers top to bottom and uses the first one whose class matches. CardDeclined is also a PaymentError, so if the PaymentError clause came first it would catch every declined card, and the specific handler would never run.