Sub topic 2
When a custom exception is worth defining
This chapter assumes you can write functions and classes, use try, except, and raise, and understand basic inheritance. It helps you decide when a built-in exception is enough and when a custom one is better.
Start with the built-ins
Python ships with exceptions for most common failures: ValueError for a bad value, TypeError for a wrong type, KeyError for a missing key, and FileNotFoundError for a missing file. A built-in exception is familiar to every Python developer, and it needs no extra code. If one of them describes your failure accurately, raise it.
def set_age(age):
if age < 0:
raise ValueError(f"age must be non-negative, got {age}")
return ageNobody needs a custom class here. ValueError says exactly what went wrong.
Signs you need a custom exception
A custom exception is worth defining when at least one of these is true.
- Callers must tell your failure apart from others. A bare
ValueErrorcan come from your code, fromint(), or from a library you call. If a caller wants to handle only your failure, they need a type that only you raise. - The failure belongs to your domain. Names like
InsufficientFundsErrororConfigErrordescribe the problem in the language of your application. Built-in names describe the problem in the language of Python. - The error carries data. A caller may need the balance and the requested amount, not just a message. A custom class can store them as attributes.
- You want one catch point for a whole package. A shared base class lets callers write a single
exceptclause for every error your library can raise.
If none of these apply, a built-in exception with a clear message is usually the better choice.
A concrete comparison
Suppose a function reads a port number from configuration. With only built-ins, the caller cannot separate "your config is bad" from other value problems.
def load_port(raw):
return int(raw)
try:
port = load_port("abc")
except ValueError:
print("Is this a config problem, or a bug somewhere else?")With a custom exception, the intent is explicit.
class ConfigError(Exception):
"""Raised when configuration is missing or invalid."""
def load_port(raw):
try:
return int(raw)
except ValueError:
raise ConfigError(f"invalid port: {raw!r}")
try:
port = load_port("abc")
except ConfigError as exc:
print(f"Configuration problem: {exc}")The except ConfigError clause cannot accidentally catch an unrelated ValueError from elsewhere. A later chapter shows how to also keep the original ValueError attached using raise ... from.
Costs to weigh
Every custom exception is part of your public interface. Callers will catch it by name, so renaming or removing it later breaks their code. It also adds documentation and tests to maintain. Define the ones that pay for themselves.
Summary of the decision
| Situation | Choice |
|---|---|
| A bad argument value, with a clear message | Built-in `ValueError` |
| A wrong argument type | Built-in `TypeError` |
| A failure specific to your application or library | Custom exception |
| Callers need structured data from the failure | Custom exception with attributes |
| You want callers to catch everything your package raises | Custom base class |
Exercise
A function parse_price(text) raises ValueError when text is not a number. Another function charge(card, amount) fails when the card is declined, and the caller needs the decline code to show the user a message. Which one should get a custom exception, and why?
Show answer
charge should get a custom exception, such as CardDeclinedError. The failure is specific to the application's domain, callers must tell it apart from other errors, and it carries data (the decline code) that fits as an attribute. parse_price can keep the built-in ValueError, because that name already describes a bad value and callers need no special handling.
Exercise
Name two costs of adding a custom exception to a library's public interface.
Show answer
Callers will catch it by name, so renaming or removing it later breaks their code. It also needs documentation and tests to maintain.