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.

Replacing a low-level exception with a more meaningful one can hide the reason an operation failed. Exception chaining preserves the original exception as the cause of the new one, keeping diagnostic context alongside the higher-level error. section 7.2.4

int dataToTransform = 0;
try {
  dataToTransform = Integer.parseInt(data);
} catch (NumberFormatException exception) {            
  throw new DataProcessingException(data, "Processing error", exception);
}

A parsing failure becomes a data-processing exception, with the original exception passed to its constructor. The constructor passes the cause to its superclass. section 7.2.4

In Python, use `raise ... from ...` to preserve the original exception when raising a custom one. In Java, pass the original exception to the custom exception’s constructor; logging it immediately is another way to retain the context. section 7.2.4

A missing cause in production

An IOException was replaced without preserving its cause, leaving logs unable to distinguish a missing file from a permission problem. A patch and redeployment were needed to recover the context; the cause was a misconfigured file path. section 7.2.4

How The Art of Code covers it

How deep it goes
Demonstrates Python chaining and passing a cause through a Java custom exception constructor.
Examples
Uses integer parsing and a production file-path failure to illustrate preserved and lost causes.
What you can do after
Apply exception chaining in Python or preserve the cause in a Java custom exception.
How it connects
Connects custom exceptions, error handling, and logging.

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.