Sub topic 1
How Python exceptions are organized
Prerequisites
This chapter assumes basic Python classes, inheritance, and the use of try, except, and raise.
The exception hierarchy
An exception is an object that reports an abnormal condition. Python organizes exception classes in an inheritance hierarchy. BaseException is the root. Most application errors inherit from Exception, which is under BaseException.
Some direct BaseException subclasses, such as KeyboardInterrupt and SystemExit, control program execution rather than report ordinary application failures. For this reason, application code usually catches Exception, not BaseException.
A custom exception is useful when callers need to distinguish a meaningful application condition from unrelated failures. For example, a payment service might need to handle InsufficientFundsError differently from a malformed request. A custom type gives callers a stable thing to catch without matching fragile message text.
When to define a custom exception
Define one when:
- The condition has domain meaning.
- Callers may recover from it or display a specific response.
- Several functions need to report the same kind of failure.
- A package needs a public error contract.
Do not create a new class merely to rename a built-in error with no added meaning. ValueError is often sufficient for an invalid argument within a small, private function.
Your first custom exception
Subclass Exception directly for an independent application error:
class ConfigError(Exception):
"""Raised when application configuration is missing or invalid."""
def require_database_url(config):
if "database_url" not in config:
raise ConfigError("missing 'database_url'")
try:
require_database_url({})
except ConfigError as exc:
print(f"Configuration failed: {exc}")The raise statement creates and propagates the exception. The except clause catches only ConfigError, leaving unrelated exceptions visible.
Naming and documenting exceptions
Use a descriptive name ending in Error, such as ConfigError or PaymentError. Give it a docstring that states when it is raised. Names should describe the condition, not the implementation detail.
For a package with related failures, define one public base class and subclass it:
class AppError(Exception):
"""Base class for errors raised by this package."""
class ConfigError(AppError):
"""Raised when configuration is invalid."""Callers can catch AppError for all package errors or catch a specific subclass when they need finer control.
Exercise
Why should application exceptions usually inherit from Exception instead of BaseException?
Show answer
Exception represents ordinary application failures, while BaseException also includes control-flow signals such as KeyboardInterrupt and SystemExit.