Sub topic 10
Wrapping Exceptions and Preserving the Cause
Sometimes a low-level problem happens deep inside your code. A number fails to parse, or a file is missing. The method that hits the problem often knows too little to explain what it means for the rest of the program. A higher-level method knows more, so it can throw its own, clearer exception.
You should still keep the original problem when you do this. If you throw it away, you lose the real reason for the failure. Exception chaining means wrapping one exception inside another. The wrapped exception is called the cause.
Why wrapping helps
Picture a program that reads a setting called port from a config file. If the value is "abc", Integer.parseInt throws a NumberFormatException. That message only says For input string: "abc", which tells the user very little. A message like "Invalid port setting in config" is much more helpful. If you also keep the original exception as the cause, the details stay available for debugging.
Passing the cause along
Most exception classes have a constructor that takes both a message and a Throwable cause. A Throwable is the parent type of every exception. You pass the caught exception in as the cause. Later, getCause() gives it back.
public class ChainDemo {
static class ConfigException extends Exception {
public ConfigException(String message, Throwable cause) {
super(message, cause);
}
}
static int readPort(String value) throws ConfigException {
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
throw new ConfigException("Invalid port setting in config: " + value, e);
}
}
public static void main(String[] args) {
try {
readPort("abc");
} catch (ConfigException e) {
System.out.println("Problem: " + e.getMessage());
System.out.println("Cause: " + e.getCause());
e.printStackTrace();
}
}
}The first two lines of output are:
Problem: Invalid port setting in config: abc
Cause: java.lang.NumberFormatException: For input string: "abc"After those lines, printStackTrace() prints the full trace. It lists the ConfigException first, followed by a section that starts with Caused by: java.lang.NumberFormatException. You read the Caused by: section the same way as a normal stack trace. It shows exactly where the original problem happened.
Other ways to set the cause
| Approach | Example | When to use |
|---|---|---|
| Constructor with cause | `new ConfigException(msg, e)` | Most of the time |
| Constructor with only a cause | `new RuntimeException(e)` | When the cause's message is enough |
| `initCause` method | `ex.initCause(e)` | When the exception class has no cause constructor |
A cause can have its own cause, which makes a chain. You can walk the chain by calling getCause() again and again until it returns null.
Exercises
Exercise
In the catch block of readPort, what changes if you write throw new ConfigException("Invalid port setting", null) instead of passing e?
Show answer
The ConfigException is still thrown, but getCause() returns null and the stack trace has no "Caused by:" section, so the original NumberFormatException and the line where it happened are lost.
Exercise
Write a loop that starts at a caught exception e and prints the class name of every exception in its cause chain.
Show answer
Throwable t = e; while (t != null) { System.out.println(t.getClass().getName()); t = t.getCause(); }