Sub topic 10
Wrapping Exceptions and Preserving the Cause
In the last chapter you wrote your own exception classes. This chapter covers what to do when a low-level error happens deep inside your code and you want to report it in your own terms. You wrap the original exception inside a new one. This is called exception chaining. Exception chaining means you attach one exception to another, so the first problem is still there to inspect.
Why Wrap an Exception at All?
Code is often built in layers. A layer is a group of code with one job. One layer reads text from a file. Another turns that text into settings. A third starts the application.
Each layer should speak its own language. Suppose a settings file contains port=80a. Deep down, Integer.parseInt throws a NumberFormatException. The code that starts your app should not have to know about number parsing. It should hear something like "the configuration is bad."
There are two simple ways to handle this, and both are bad:
- Let the low-level exception escape. The caller gets a
NumberFormatExceptionwith no hint that it came from the config file. - Throw a new exception and drop the old one. The caller gets a clear message, but the real details are gone, such as which text failed and on which line.
Wrapping gives you both. The new exception carries a clear, high-level message, and it also holds the original exception as its cause. The cause is the exception that led to the current one.
The Cause Constructor
Every exception class in Java extends Throwable. Throwable has four constructors, and two of them accept a cause.
| Constructor | Message | Cause |
|---|---|---|
| `Throwable()` | none (`null`) | none |
| `Throwable(String message)` | your message | none |
| `Throwable(String message, Throwable cause)` | your message | the exception you pass |
| `Throwable(Throwable cause)` | `cause.toString()` | the exception you pass |
Exception and RuntimeException offer the same four constructors. Your own exception class does not get them for free, though. In Java, a class does not inherit constructors. You must write the cause constructor yourself and pass the cause on with super(message, cause). That is why the custom exception in the previous chapter had a second constructor.
A Complete Example
This program reads a port number from text. If parsing fails, it wraps the failure in a checked ConfigException.
public class ChainDemo {
static class ConfigException extends Exception {
ConfigException(String message, Throwable cause) {
super(message, cause);
}
}
static int readPort(String text) throws ConfigException {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
throw new ConfigException("Bad port setting: \"" + text + "\"", e);
}
}
public static void main(String[] args) {
try {
readPort("80a");
} catch (ConfigException e) {
System.out.println("Problem: " + e.getMessage());
System.out.println("Cause: " + e.getCause());
}
}
}Save it as ChainDemo.java, then run javac ChainDemo.java and java ChainDemo. The output is:
Problem: Bad port setting: "80a"
Cause: java.lang.NumberFormatException: For input string: "80a"Here is what happens, step by step:
Integer.parseInt("80a")throws aNumberFormatException.- The
catchblock inreadPortcatches it ase. - The
catchblock creates aConfigExceptionand passeseas the second argument. That argument becomes the cause. maincatches theConfigException.getMessage()returns the high-level message, andgetCause()returns the original exception.
How a Chain Looks in a Stack Trace
If nobody catches a wrapped exception, Java prints the whole chain. Change main to declare throws ConfigException and call readPort("80a") without a try. The output looks roughly like this (line numbers vary):
Exception in thread "main" ChainDemo$ConfigException: Bad port setting: "80a"
at ChainDemo.readPort(ChainDemo.java:12)
at ChainDemo.main(ChainDemo.java:17)
Caused by: java.lang.NumberFormatException: For input string: "80a"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:778)
at ChainDemo.readPort(ChainDemo.java:10)
... 1 moreRead it from top to bottom:
- The first block is the outer exception, the one your code threw.
- The
Caused by:line starts the inner exception. If the inner exception had its own cause, anotherCaused by:block would follow. ... 1 moremeans one more stack line is the same as a line already shown above, hereChainDemo.main. Java leaves it out to save space.
When you debug, the last Caused by: block is usually the most useful one. It shows where the trouble really started.
Walking the Whole Chain
A chain can have more than two links. You can follow it with a loop. Call getCause() again and again until it returns null.
public class ChainWalk {
static class ConfigException extends Exception {
ConfigException(String message, Throwable cause) {
super(message, cause);
}
}
static int readPort(String text) throws ConfigException {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
throw new ConfigException("Bad port setting", e);
}
}
static void startServer() {
try {
readPort("80a");
} catch (ConfigException e) {
throw new IllegalStateException("Server could not start", e);
}
}
public static void main(String[] args) {
try {
startServer();
} catch (IllegalStateException e) {
Throwable t = e;
while (t != null) {
System.out.println(t.getClass().getSimpleName() + ": " + t.getMessage());
t = t.getCause();
}
}
}
}Output:
IllegalStateException: Server could not start
ConfigException: Bad port setting
NumberFormatException: For input string: "80a"startServer wraps a checked exception inside an unchecked one. This is common when a method cannot add a throws clause, or when the caller can't do anything useful to recover. The Java library does the same thing with java.io.UncheckedIOException, which wraps an IOException.
Setting a Cause Later with initCause
Some older exception classes have no constructor that takes a cause. For those, you can create the exception first and attach the cause afterwards with initCause.
public class InitCauseDemo {
public static void main(String[] args) {
IllegalStateException wrapper = new IllegalStateException("startup failed");
wrapper.initCause(new ArithmeticException("/ by zero"));
System.out.println(wrapper.getCause());
}
}This prints java.lang.ArithmeticException: / by zero.
Common Mistakes
| Mistake | What goes wrong | Fix |
|---|---|---|
| `throw new ConfigException("bad port");` inside a `catch` | The original exception and its stack trace are lost | Pass `e` as the cause |
| `throw new ConfigException(e.getMessage());` | Only the text survives. The type and stack trace are lost | Pass `e` as the cause and write a clearer message |
| Custom exception has no `(String, Throwable)` constructor | Callers cannot chain, even if they want to | Add the constructor and call `super(message, cause)` |
| Wrapping every exception "just because" | Long chains that say nothing new | Wrap only when you add meaning, such as switching to your layer's terms |
| Printing the error and also wrapping it | The same error appears in the logs twice | Either handle and log it, or wrap and rethrow it. Don't do both |
Summary
- Exception chaining lets you report a problem in high-level terms and still keep the low-level details.
- Pass the original exception as the
causeargument to a constructor, then read it back withgetCause(). - Your custom exceptions need their own
(String message, Throwable cause)constructor. - Stack traces show each link of the chain after a
Caused by:line. The last link is usually the root of the problem. initCauseattaches a cause after construction, but only once.
Exercise
This catch block hides useful information. Rewrite it so the caller can still see the original exception, and name the method the caller would use to get it. catch (NumberFormatException e) { throw new ConfigException("Invalid timeout value"); }
Show answer
Pass the caught exception as the cause: throw new ConfigException("Invalid timeout value", e);. ConfigException must have a constructor ConfigException(String message, Throwable cause) that calls super(message, cause). The caller gets the original NumberFormatException back with getCause(), and an uncaught stack trace will show it after a "Caused by:" line.
Exercise
A stack trace shows three blocks: one starting with "Exception in thread main AppException", then "Caused by: DatabaseException", then "Caused by: java.net.ConnectException: Connection refused". Which block should you look at first to find where the problem started, and why?
Show answer
Look at the last block, "Caused by: java.net.ConnectException: Connection refused". Each "Caused by:" is the exception that led to the one above it, so the last block is the root cause. Here the program could not connect to the database server. The outer exceptions only wrap that failure in higher-level terms.