Sub topic 4
Naming and documenting exceptions
This chapter assumes you can subclass Exception and raise and catch it, as covered in the previous chapters. Here you will learn how to choose a name that reads well in a traceback and how to write a docstring that tells callers when to expect the exception.
Why the name matters
An exception name appears in three places: the raise line, the except clause, and the last line of every traceback. Someone debugging a failure often sees only the name. A good name lets them guess the cause without opening your code.
Naming conventions
PEP 8 gives the rules most Python code follows:
- Use CapWords, like all class names:
ConfigError, notconfig_error. - End the name with
Errorwhen the class represents an error. This matches built-ins such asValueErrorandKeyError. - Describe what went wrong, not where it happened.
InsufficientFundsErrorsays more thanBankError2. - Avoid repeating the module name. In a module called
config, preferconfig.ParseErroroverconfig.ConfigParseError.
| Weak name | Better name | Reason |
|---|---|---|
| `MyException` | `ConfigError` | Says what area failed |
| `Error1` | `MissingKeyError` | Says what went wrong |
| `bad_input` | `InvalidInputError` | CapWords and `Error` suffix |
| `DatabaseProblem` | `DatabaseConnectionError` | Uses the standard suffix and is more specific |
The Error suffix has an exception. If the class signals a condition that is not a failure, such as a signal to stop, use no suffix or Exception. The built-in StopIteration and KeyboardInterrupt follow this pattern.
Writing the docstring
A docstring is the string literal placed first in the class body. For an exception, it should answer one question: when is this raised?
- Start with a one-line summary in the form "Raised when ...".
- Add a second paragraph only if callers need more, such as attributes they can read or a way to recover.
- Do not add
pass. The docstring is a complete class body.
class AppError(Exception):
"""Base class for errors raised by this application."""
class ConfigError(AppError):
"""Raised when configuration is missing or invalid."""
class MissingKeyError(ConfigError):
"""Raised when a required configuration key is absent.
Catch ConfigError instead if you do not need to tell
missing keys apart from other configuration problems.
"""
print(MissingKeyError.__doc__.splitlines()[0])
print(issubclass(MissingKeyError, AppError))The code prints Raised when a required configuration key is absent. and then True. Tools such as help(), IDE tooltips, and documentation generators read the same docstring, so callers see it without opening your source.
Documenting where it is raised
The exception's own docstring says when it occurs. The function that raises it should also list it, so callers know what to catch. A Raises: section is a common convention.
class AppError(Exception):
"""Base class for errors raised by this application."""
class ConfigError(AppError):
"""Raised when configuration is missing or invalid."""
def load_port(raw):
"""Convert a raw string to a TCP port number.
Raises:
ConfigError: If raw is not an integer.
"""
try:
return int(raw)
except ValueError as exc:
raise ConfigError(f"invalid port: {raw!r}") from exc
print(load_port("8080"))Common mistakes
- Giving a vague name such as
CustomError. It tells the reader nothing theExceptionbase class did not. - Skipping the docstring because the name seems obvious. The docstring is where you say when the exception is raised and which base class to catch.
- Naming an exception after the function that raises it. Names that follow the cause stay valid when the code is refactored.
Exercise
You are writing a module called payments and want an exception for a card that has expired. Which name follows the conventions in this chapter: ExpiredCardError, PaymentsExpiredCard, or payment_error? Write the first line of its docstring.
Show answer
ExpiredCardError. It uses CapWords, ends in Error, describes what went wrong, and does not repeat the module name. A suitable first line is """Raised when a payment card is past its expiry date.""".