Errors
Exception Chaining
Catch the low-level exception where it happens, then raise a domain-specific exception from it.
Source
class ConfigError(Exception):
pass
def read_port(text):
try:
return int(text)
except ValueError as error:
raise ConfigError("port must be a number") from error
print(ConfigError.__name__)Output
ConfigErrorThe caller handles the domain error. The original ValueError remains available as __cause__.
Source
try:
read_port("abc")
except ConfigError as error:
print(error)
print(type(error.__cause__).__name__)Output
port must be a number
ValueErrorNotes
- Use
raise ... from errorwhen translating exceptions across a boundary. - The new exception's
__cause__points to the original exception. - Chaining keeps user-facing errors clear without losing debugging context.
See also
- builds on: Exceptions
- related: Custom Exceptions
- related: Assertions
Run the complete example
Expected output
ConfigError
port must be a number
ValueError
Execution time appears here after you run the example.