Sub topic 2
Raising and Catching Your Exception
Assume you know Python functions, classes, inheritance, and try/except/raise. A custom exception is useful when callers need to distinguish one failure in your application from other failures.
Raise and catch a custom exception
Define the exception by inheriting from Exception. Raise it where the invalid condition occurs, then catch it where the program can respond.
class ConfigError(Exception):
"""Raised when application configuration is invalid."""
def load_port(raw_port):
try:
return int(raw_port)
except ValueError as exc:
raise ConfigError(f"invalid port: {raw_port!r}") from exc
try:
port = load_port("web")
except ConfigError as exc:
print(f"Configuration failed: {exc}")raise stops normal execution and creates an exception object. The except block catches a matching type. Catch the narrowest type that you can handle. Avoid catching Exception when you only expect ConfigError, because that can hide unrelated programming errors.
Build a common hierarchy
A package can define one base exception for all errors that callers may want to handle together. More specific exceptions inherit from that base.
class AppError(Exception):
"""Base class for errors raised by this application."""
class ConfigError(AppError):
"""Raised when configuration is missing or invalid."""
class PaymentError(AppError):
"""Raised when a payment cannot be completed."""
try:
raise ConfigError("missing 'database_url'")
except AppError as exc:
print(f"{type(exc).__name__}: {exc}")Catching AppError catches both current and future application-specific subclasses, but it does not catch unrelated errors such as KeyError.
Carry data on an exception
Store values that callers may need as attributes. Pass the same constructor arguments to Exception.__init__ so args remains consistent.
class InsufficientFundsError(AppError):
"""Raised when a withdrawal exceeds the available balance."""
def __init__(self, balance, amount):
super().__init__(balance, amount)
self.balance = balance
self.amount = amount
def __str__(self):
return f"Cannot withdraw {self.amount}; balance is {self.balance}"
try:
raise InsufficientFundsError(balance=50, amount=80)
except InsufficientFundsError as exc:
print(exc) # Cannot withdraw 80; balance is 50
print(exc.amount - exc.balance) # 30Attributes provide structured data without forcing callers to parse a message. __str__ controls the readable text shown to users and logs.
Exercise
Why does except AppError catch ConfigError?
Show answer
ConfigError inherits from AppError, so it is an instance of that base class.