liveBook · Manning

Exception chaining

As explained in The Art of Code

Exception chaining is the preservation of an underlying exception as the cause of a newly raised exception.

Exception chaining preserves the original failure when code raises a higher-level, domain-specific error. It keeps the readable new error while retaining diagnostic context such as whether parsing failed because of a missing file, permission issue, or bad input. section 7.2.4

class DataProcessingError(Exception):
    pass

try:
    data_to_transform = int(data)
except ValueError as exception:
    raise DataProcessingError(f"Processing error for input: {data}") from
exception

Catch a low-level ValueError, raise a DataProcessingError that explains the operation, and chain it to the caught exception with `raise ... from exception`. section 7.2.4

Use chaining whenever translating technical failures across a layer boundary. A custom exception tells callers what operation failed; its preserved cause tells operators and logs why it failed. Replacing the cause loses information and can turn an obvious configuration problem into a redeployment-worthy investigation. section 7.2.4

How The Art of Code covers it

How deep it goes
Demonstrates Python `raise ... from` and Java constructor causes through parsing-error wrapping.
Examples
Uses NumberFormatException and ValueError parsing failures wrapped as DataProcessingException or DataProcessingError.
What you can do after
Apply it to retain original causes when raising a clearer higher-level exception.
How it connects
Connects custom exceptions, exception causes, logging, technical failures, and business logic errors.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Art of Code. The section links point to the parts of the book it draws on.