Skip to main content
Exception handling · Topic 6 of 7

Exception chaining

Definition​

Exception chaining means wrapping a low-level exception inside a higher-level one and keeping the original as its cause. The caller gets a meaningful message, and the full story is still available through getCause().

Example code​

Wrapping a parse error in a service error

class ConfigException extends RuntimeException {
ConfigException(String message, Throwable cause) {
super(message, cause); // keep the original as the cause
}
}

class Demo {
static int readPort(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
throw new ConfigException("Invalid server port in config", e);
}
}

public static void main(String[] args) {
try {
readPort("80x");
} catch (ConfigException e) {
System.out.println(e.getMessage());
System.out.println("Caused by: " + e.getCause());
}
}
}

// Output:
// Invalid server port in config
// Caused by: java.lang.NumberFormatException: For input string: "80x"

Finished this page? Track your progress (saved only in your browser).