Sub topic 2
When a custom exception is worth defining
What this chapter assumes
You should be comfortable with basic Python syntax, functions and classes. You should also know how try, except and raise work, and how a subclass calls super().__init__. This chapter does not teach the mechanics of writing an exception class. The next chapters do that. Here you learn how to decide whether to write one at all.
Python lets you define an exception in two lines, so it is tempting to define one for every error. Each custom exception becomes part of your code's public interface. Other code will catch it, tests will check for it, and you will have to keep it stable. Define one only when it earns that cost.
What the built-in exceptions already give you
Python ships with exceptions for most common failures:
ValueError: the argument has the right type but an unacceptable value.TypeError: the argument has the wrong type.KeyErrorandIndexError: a lookup failed.FileNotFoundErrorandPermissionError: file system problems.NotImplementedError: a subclass must supply the behavior.RuntimeError: a general failure that fits nowhere else.
Readers of your code already know what these mean, and they need no documentation from you. If a function is given -5 as an age and raises ValueError("age must not be negative"), no one is surprised. A custom exception adds a new name to learn. Prefer a built-in when it describes the problem accurately and no caller needs to treat that problem differently from other problems of the same type.
Signs that a custom exception is worth it
Four signs are worth checking for. If none apply, use a built-in.
1. Callers must tell your failure apart from others
Suppose a function can raise ValueError for two unrelated reasons.
def load_port(raw):
port = int(raw) # raises ValueError for text such as "abc"
if not 1 <= port <= 65535:
raise ValueError(f"port out of range: {port}")
return port
try:
load_port("abc")
except ValueError as exc:
print("caught:", exc)The except ValueError clause catches both the failed conversion and the range check. It would also catch a ValueError from a bug somewhere inside a helper that load_port calls. The caller cannot tell these cases apart without reading the message text, and message text is not a stable interface.
A dedicated exception fixes this. The following sketch uses the class without explaining its construction, which the next chapter covers.
class ConfigError(Exception):
"""Raised when configuration is missing or invalid."""
def load_port(raw):
try:
port = int(raw)
except ValueError as exc:
raise ConfigError(f"invalid port: {raw!r}") from exc
if not 1 <= port <= 65535:
raise ConfigError(f"port out of range: {port}")
return port
try:
load_port("abc")
except ConfigError as exc:
print("bad configuration:", exc)Now except ConfigError means exactly one thing: the configuration is wrong. A stray ValueError from a bug is not swallowed by that handler, so it still surfaces as a real defect.
2. The failure has a meaning in your problem domain
Names such as InsufficientFundsError, OrderAlreadyShippedError or RateLimitExceeded describe what happened in the language of the application. A traceback ending in InsufficientFundsError tells a maintainer more than one ending in ValueError. This helps most when the error crosses several layers before anyone reads it, such as logs, monitoring alerts or an API response.
3. Callers want to catch a whole family at a boundary
A library often wants its users to write one handler for "anything this library raised". That needs a shared base class.
class AppError(Exception):
"""Base class for errors raised by this application."""
class ConfigError(AppError):
"""Raised when configuration is missing or invalid."""
try:
raise ConfigError("missing 'database_url'")
except AppError as exc:
print(f"{type(exc).__name__}: {exc}")Without a base class, callers must list every built-in exception your code might raise, and they still cannot separate your errors from those of other libraries. This is the strongest reason to define exceptions for a package. A later chapter covers hierarchy design.
4. The error carries data a handler needs
If a handler must act on facts about the failure, such as the amount that was too large or the field that was invalid, give the exception attributes. Callers then read exc.amount instead of parsing a message string. A built-in exception has no place for that data. A later chapter shows how to add it safely.
A decision flow
The following diagram turns the four signs into a short sequence of questions.
The first branch matters: if no built-in describes the problem accurately, raising a misleading one is worse than defining a new one. Raising ValueError for a failed network call, for example, sends the reader looking for a bad argument that does not exist.
What a custom exception costs
Weigh the benefits against the ongoing cost.
- Public interface. Once users write
except ConfigError, you cannot rename it, move it to another module or change its base class without breaking them. - Documentation. Callers need to know which functions raise it and when.
- Surface area. Twenty exception classes for a small module make the code harder to learn than twenty lines of clear messages.
- Pressure to keep a hierarchy consistent. Each class asks where it belongs in the family tree.
A rough rule: if you cannot name a piece of code that would catch the exception and behave differently from a generic handler, you probably do not need it.
Situations that look like they need one but usually do not
| Situation | Better choice | Reason |
|---|---|---|
| A function receives an argument of the wrong type | `TypeError` | This signals a programming mistake, and `TypeError` is the convention. |
| A value is out of range, and nobody will handle it specifically | `ValueError` | Everyone recognizes it. |
| A dictionary key is missing | `KeyError` | Callers already know how to handle it. |
| A method must be overridden | `NotImplementedError` | It is the standard signal for abstract behavior. |
| You want a different message for each failure site | One exception with different messages | Messages vary freely. Classes should vary only when handling varies. |
| An exception would exist only to carry one string | A built-in with that string | A class that adds nothing is noise. |
Two thought experiments
A library that parses invoices. Callers want to show the user "this invoice file is malformed" but let genuine bugs crash with a traceback. That requires an exception that means "malformed input" and nothing else, so InvoiceParseError is justified. It also tells you where to use raise ... from, so the original KeyError or ValueError is kept as the cause. A later chapter covers that.
A one-file script. It reads a number from the command line and exits with a message if the value is negative. No other code calls it, so no caller needs to distinguish anything. A ValueError and a clear message are enough. A custom class here would add lines and no behavior.
Checking whether you chose well
You can test the decision by writing the caller first. Sketch the except clause that will handle your failure.
try:
port = load_port(raw_value)
except ConfigError as exc:
print(f"Fix your settings: {exc}")
raise SystemExit(2)If the clause reads naturally and differs from what you would do for other errors, the exception has a clear job. If the best clause you can write is except Exception, a custom class will not improve the situation.
Also check how the exception will be tested. A test that asserts pytest.raises(ConfigError) is stronger than one asserting pytest.raises(ValueError), because the second passes when an unrelated bug raises ValueError. When you want a failing test to point at one specific cause, that is a sign the exception deserves its own type.
Summary of the decision
- Use a built-in when it describes the failure accurately and no caller must treat it specially.
- Define a custom exception when callers must separate your failure from others, when the failure has domain meaning, when callers want a family to catch, or when the handler needs data.
- Keep the number of exception classes small, and give each one a handling difference that justifies it.
- Leave programming errors, such as wrong types, as their built-in types.
The next chapter shows how to write the class itself.
Exercise
A function get_user(user_id) raises KeyError when the id is not in a dictionary of users. Your colleague proposes a new UserNotFoundError(Exception). Name two conditions under which this is worth doing, and one under which it is not.
Show answer
It is worth doing when callers must distinguish a missing user from other KeyErrors, such as a KeyError from a bug elsewhere in the code. It is also worth doing when the package wants one base class so callers can catch all of its errors together, with UserNotFoundError as a subclass of it. A handler that needs the id as data is a third reason. It is not worth doing when the function is used only inside one module, no code handles the failure specially, and a plain KeyError is already clear.
Exercise
The function below raises ValueError for two different reasons. Rewrite it so a caller can handle the "not a number" case separately from the "negative" case without reading message text. Use at most two custom exceptions, and make clear which one a caller would catch for each case.
def parse_quantity(raw):
n = int(raw)
if n < 0:
raise ValueError("quantity must not be negative")
return n
Show answer
One solution defines class QuantityError(Exception) as a base class and class NegativeQuantityError(QuantityError). The function wraps the int conversion:
class QuantityError(Exception):
"""Base class for invalid quantities."""
class NegativeQuantityError(QuantityError):
"""Raised when a quantity is below zero."""
def parse_quantity(raw):
try:
n = int(raw)
except ValueError as exc:
raise QuantityError(f"not a number: {raw!r}") from exc
if n < 0:
raise NegativeQuantityError("quantity must not be negative")
return n
A caller catches NegativeQuantityError for the negative case, and QuantityError for the not-a-number case or for any quantity problem. The order of except clauses matters: put the subclass first.