Sub topic 12
Defining your own exception classes
This chapter assumes you can write try/except blocks, know that exceptions form a class hierarchy under BaseException and Exception, and can write a basic subclass.
Why define your own
Built-in exceptions such as ValueError describe what went wrong in general terms. They don't say which part of your program failed. If a caller catches ValueError around a call to your library, they will also catch unrelated ValueErrors raised deep inside it. A custom exception gives callers a specific type to catch, and it names the failure in your application's own vocabulary.
The minimal version
Subclass Exception, not BaseException. BaseException is reserved for things like KeyboardInterrupt and SystemExit, which ordinary handlers should not intercept. A docstring is enough for the class body.
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 raise ... from exc form keeps the original ValueError available as __cause__. The caller sees a ConfigError but can still inspect what triggered it.
Build a small hierarchy
For anything beyond a single script, define one base class for your package and derive specific errors from it. Callers can then catch one error or the whole family.
Because of the hierarchy, except ConfigError also catches MissingKeyError. Handler order still matters. Put the more specific class first when you have several except clauses.
Carry data on the exception
An exception can hold structured data in attributes, so handlers don't need to parse the message text. Pass the message to super().__init__() so that str(err) and tracebacks still work.
class AppError(Exception):
"""Base class for all errors raised by this package."""
class ConfigError(AppError):
"""Raised when configuration is invalid."""
class MissingKeyError(ConfigError):
def __init__(self, key):
super().__init__(f"missing key: {key}")
self.key = key
def read_setting(config, key):
try:
return config[key]
except KeyError as exc:
raise MissingKeyError(key) from exc
try:
read_setting({"host": "localhost"}, "port")
except ConfigError as err:
print(err)
print(err.key)This prints missing key: port and then port. The handler catches the broader ConfigError and still reads err.key, which exists on the MissingKeyError instance.
Common errors
- Inheriting from
BaseException. A broadexcept Exceptionwill miss your error, and it can bypass normal shutdown handling. - Skipping
super().__init__(). If you override__init__without calling it,err.argsis empty and the traceback message may be blank. - Too many classes. Add a subclass only when a caller would handle that case differently. If every caller treats two failures the same way, one class is enough.
- Naming. End class names with
Error, as the standard library does, such asConfigError.
Exercise
You write class QuotaError(BaseException): pass and raise it inside a function. A caller wraps the call in try: ... except Exception: .... Does the handler catch the error? What should you change?
Show answer
No. QuotaError derives from BaseException directly, not from Exception, so except Exception does not match it and the error propagates. Change the base class to Exception, or better, to your package's base error such as AppError, which itself derives from Exception.
Exercise
Given class AppError(Exception) and class ConfigError(AppError), which clause order is correct for catching both, and why? Option 1: except AppError then except ConfigError. Option 2: except ConfigError then except AppError.
Show answer
Option 2. Python checks clauses top to bottom and runs the first one that matches. A ConfigError is also an AppError, so in option 1 the AppError clause would catch it first and the ConfigError clause could never run.