liveBook · Manning

Custom exception

As explained in The Art of Code

A custom exception is an application-defined exception type whose name and structure represent a specific failure condition.

A custom exception is an application-defined exception type named for a specific failure. At a business layer, API boundary, or user-facing interface, it can translate a technical failure into a meaningful domain error. section 7.2.4

Choose an intention-revealing name, even if the class is otherwise small. Keep captured data immutable, and preserve the original cause so technical details remain available for diagnosis rather than exposed to users or clients. section 7.2.4

public class DataProcessingException extends Exception {
 private final String data;

 public DataProcessingException(String data, 
   String message, Exception exception) {
   super(message, exception);
   this.data = data;
 }
}

This Java exception captures the input and passes the original exception to its superclass. 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 named processing failure without losing its cause. section 7.2.4

In Python, use exception chaining with `raise ... from ...` to preserve the original error. Let a higher layer decide how to handle a failure when a low-level action lacks the broader context. section 7.2.4

How The Art of Code covers it

How deep it goes
Demonstrates defining and throwing custom exceptions, including immutable captured data and preservation of the original cause.
Examples
Uses data parsing failures and invalid order IDs to illustrate named exceptions.
What you can do after
Build a custom exception from scratch to name a failure and preserve its original cause.
How it connects
Connects custom exceptions with exception chaining, logging, domain errors, and error handling across layers.

Also explained in

Compare how 3 books explain custom exception →

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.