Sub topic 3
Controlling the Message and `args`
Assume you know Python classes, inheritance, try/except, and raise. This chapter focuses on how a custom exception stores its constructor arguments and displays its message.
Messages and `args`
An exception stores positional constructor arguments in its args attribute. If you add structured data, pass the same values to Exception.__init__. Then define __str__ when you want a friendlier message.
class InsufficientFundsError(Exception):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(balance, amount)
def __str__(self):
return f"Cannot withdraw {self.amount}; balance is {self.balance}"
error = InsufficientFundsError(50, 80)
print(error) # Cannot withdraw 80; balance is 50
print(error.args) # (50, 80)Keeping args aligned with __init__ helps Python rebuild the exception during copying or pickling. Passing only a formatted message can make reconstruction fail when the constructor needs multiple values.
Preserving the Cause with `raise from`
When a low-level exception explains why an operation failed, chain it to a higher-level exception:
class ConfigError(Exception):
pass
def load_port(raw):
try:
return int(raw)
except ValueError as exc:
raise ConfigError(f"invalid port: {raw!r}") from excThe new exception is shown to callers, while __cause__ preserves the original ValueError.
Notes and Tests
Python 3.11 and later let you add context without changing the exception type or message:
error = ConfigError("configuration failed")
error.add_note("Read settings from production.toml")Test both the type and important message text with pytest.raises:
import pytest
def test_invalid_port():
with pytest.raises(ConfigError, match="invalid port") as info:
load_port("abc")
assert isinstance(info.value.__cause__, ValueError)Mistakes to Avoid
- Do not catch
Exceptionwhen a specific custom type is enough. - Do not create a new exception for every small condition.
- Do not discard the original cause when translating errors.
- Do not store only human-formatted data when callers need structured attributes.
- Do not change constructor arguments without considering pickling and copying.
Exercise
Why should InsufficientFundsError pass balance and amount to super().__init__?
Show answer
It keeps args consistent with the constructor, which supports readable behavior and safer copying or pickling.