Wrapping and messages
An exception is a report to somebody who was not there. Three things decide whether that report is useful: the message says what value was wrong and what was expected, the cause keeps the lower-level failure, and the catch that handles it is narrow enough to leave the bugs alone. This lesson has a program for each.
A message with the value
The message of NumberFormatException says For input string: "x", which is a start, and it does not say what the method wanted. The program wraps it in an exception whose message carries the bad value and the range, and keeps the original as the cause:
public class Messages {
public static void main(String[] args) {
System.out.println(safeParse("42"));
for (String bad : new String[] {"x", "", "3.5"}) {
try {
System.out.println(safeParse(bad));
} catch (IllegalArgumentException e) {
System.out.println("bad: " + e.getMessage());
}
}
}
static int safeParse(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(
"expected a whole number in the range 0..99, got '" + text + "'", e);
}
}
}
javac -Xlint:all Messages.java
java Messages
42
bad: expected a whole number in the range 0..99, got 'x'
bad: expected a whole number in the range 0..99, got ''
bad: expected a whole number in the range 0..99, got '3.5'
The empty value is the case a message built from a template alone gets wrong: it prints nothing where the value was, and a reader cannot tell whether the input was empty or the code forgot it. The quotes around the value are what make the empty one visible, and they are the cheapest improvement a message can have.
Wrapping a checked exception
A method that reads a file may not want to declare IOException: a caller of a small configuration reader has nothing useful to do with it. The JDK has an unchecked wrapper for exactly this, UncheckedIOException, and the cause keeps the original:
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class Wrapping {
public static void main(String[] args) {
System.out.println(read("missing.txt"));
try {
readOrFail("missing.txt");
} catch (UncheckedIOException e) {
System.out.println("unchecked: " + e.getMessage());
System.out.println("cause: " + e.getCause().getClass().getSimpleName());
}
}
static String read(String file) {
try {
return Files.readString(Path.of(file), StandardCharsets.UTF_8);
} catch (java.io.IOException e) {
return "(missing)";
}
}
static String readOrFail(String file) {
try {
return Files.readString(Path.of(file), StandardCharsets.UTF_8);
} catch (java.io.IOException e) {
throw new UncheckedIOException("cannot read " + file, e);
}
}
}
javac -Xlint:all Wrapping.java
java Wrapping
(missing)
unchecked: cannot read missing.txt
cause: NoSuchFileException
The first method answers a default and the second refuses, and neither makes its caller handle an I/O exception. The two are a design choice the reader can see in the signature: one returns a value that may be the default, the other throws. The file classes are lesson 105; here they are only a source of a checked exception.
The wrapper is the right tool when the caller cannot act and the method is used inside a lambda or a stream, where a checked exception does not fit at all (lesson 092). It is the wrong tool when the caller can act: then the checked type is information, not noise.
The catch that hides a bug
The bug below is a null in an array, and the catch of Exception turns it into a line of output:
public class Swallow {
public static void main(String[] args) {
String[] values = {"a", null};
try {
for (String value : values) {
System.out.println(value.length());
}
} catch (Exception e) {
System.out.println("ignored: " + e.getClass().getSimpleName());
}
}
}
javac -Xlint:all Swallow.java
java Swallow
1
ignored: NullPointerException
The program ran, printed, and lost the line number, the loop and the array index that a stack trace would have named. A NullPointerException is a bug in this code and not a condition of the input, so the right program either checks the value or lets the exception out. The broad catch is only right at the top of a program that has to keep running, and there it logs the exception itself.
A catch that cannot happen
The compiler also checks the other direction: a checked exception in a catch must be possible in the try, or the catch is dead code and the build fails:
import java.io.IOException;
public class Never {
public static void main(String[] args) {
try {
System.out.println("nothing risky here");
} catch (IOException e) {
System.out.println("unreachable");
}
}
}
javac -Xlint:all Never.java
Never.java:7: error: exception IOException is never thrown in body of corresponding try statement
} catch (IOException e) {
^
1 error
The message names the type and the block. The rule is why a catch (Exception e) is allowed while catch (IOException e) is not: the unchecked branch can always be thrown, so the broad catch is never known to be dead.
The design rules
Say what was wrong and what was expected, with the value in quotes. Keep the cause when the exception comes from somewhere else. Catch the narrowest type that can happen and that the code can do something about. Do not catch Exception around a large block, and never write an empty catch. Let the exception out of a lambda only if you wrap it, and then wrap it with the cause. A failure that a person will read deserves a sentence, and a failure that a program will act on deserves a field, which is where lesson 097 started.
Exercises
- Change the message of Messages to name the maximum as well and print the three bad lines again.
- Make read answer an empty string instead of a default and explain which caller breaks.
- Narrow the catch of Swallow to NullPointerException and add a check for the null element.
- Add a catch (IOException e) around a System.out.println and read the error.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a useful exception message contain?
Answer
The value that was wrong, in quotes, and what was expected
The reader was not there, so the message has to say what the input was and what the method wanted.
-
Why is
UncheckedIOExceptionuseful?Answer
It carries an IOException as its cause without adding a throws clause
The wrapper keeps the original failure and lets a method sit inside a lambda or a stream.
-
Why is a broad catch of Exception a problem?
Answer
It catches the bugs of the block as well and hides where they happened
An unchecked bug is caught with the expected failures and loses its stack trace.
-
What does the cause of a wrapper exception keep?
Answer
The original failure, with its class and its trace
The cause is the link from the high-level report back to the real failure.
-
When is a catch of a checked type refused by the compiler?
Answer
When the try body cannot throw that type
The catch would be dead code, which is the Never program of this lesson.
-
What is wrong with a message built only from a template, such as "bad input"?
Answer
It names neither the value nor what was expected
The reader has to guess the input, and the empty value becomes invisible.
-
What does this program print?
public class Q1 { public static void main(String[] args) { try { Integer.parseInt(""); } catch (NumberFormatException e) { System.out.println("caught " + e.getClass().getSimpleName()); } } }Answer
caught NumberFormatException
The catch prints only the class name here, and the empty string cannot be parsed.
-
What does this program print?
public class Q2 { static int parse(String s) { try { return Integer.parseInt(s); } catch (NumberFormatException e) { throw new IllegalArgumentException("bad: [" + s + "]", e); } } public static void main(String[] args) { try { parse("x"); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); System.out.println(e.getCause().getClass().getSimpleName()); } } }Answer
bad: [x] / NumberFormatException
The wrapper carries its own message and the original as the cause.
-
What does this program print?
public class Q3 { public static void main(String[] args) { String[] values = {"ab", null}; for (String value : values) { try { System.out.println(value.length()); } catch (NullPointerException e) { System.out.println("null element"); } } } }Answer
2 / null element
The first value prints its length and the null one is caught and reported.
-
What does the quotes around a value in a message achieve?
Answer
An empty value stays visible instead of leaving a gap
Without the quotes an empty string looks like a missing part of the sentence.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev