Exceptions
An exception is how a method reports that it could not do its job. Java splits them in two: a checked exception is part of the method's signature, so a caller cannot compile without deciding what to do; an unchecked one is a programming error that the compiler does not track. The whole syntax is try, catch, finally, and this lesson reads each part from a run.
Checked and unchecked
Class.forName throws a checked ClassNotFoundException, and the call does not compile without a catch or a throws. Integer.parseInt throws an unchecked NumberFormatException, and an array access throws an unchecked ArrayIndexOutOfBoundsException: the program may catch them, and it may not.
public class Kinds {
public static void main(String[] args) {
try {
Object loaded = Class.forName("no.such.Class");
System.out.println(loaded);
} catch (ClassNotFoundException e) {
System.out.println("checked: " + e.getClass().getSimpleName());
}
try {
Integer.parseInt("12x");
} catch (NumberFormatException e) {
System.out.println("unchecked: " + e.getClass().getSimpleName());
}
try {
int[] numbers = new int[2];
numbers[3] = 1;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("unchecked: " + e.getMessage());
}
}
}
javac -Xlint:all Kinds.java
java Kinds
checked: ClassNotFoundException
unchecked: NumberFormatException
unchecked: Index 3 out of bounds for length 2
The first name is the requirement: a checked exception must be handled, because the compiler will not let the call through otherwise. The other two are warnings a careful program handles and a lazy one ignores, and the second message is the one a program prints when it wants to say which index was wrong.
finally
A finally block runs on every path out of the try: the normal end, a return, a throw or an exception the program does not catch. The program prints from it in both branches, and then shows the case the compiler warns about:
public class Finally {
public static void main(String[] args) {
System.out.println(withFinally(false));
System.out.println(withFinally(true));
System.out.println(finallyWins());
}
static String withFinally(boolean fail) {
try {
if (fail) {
throw new IllegalStateException("failed");
}
return "returned from try";
} catch (IllegalStateException e) {
return "returned from catch";
} finally {
System.out.println("finally runs: " + fail);
}
}
static String finallyWins() {
try {
return "try";
} finally {
return "finally";
}
}
}
javac -Xlint:all Finally.java
java Finally
Finally.java:26: warning: [finally] finally clause cannot complete normally
}
^
1 warning
finally runs: false
returned from try
finally runs: true
returned from catch
finally
The line order is the important part: the message of the finally comes before the value the method answers, because the value is printed after the call returns, and the call returns after finally has run. The last case is the warning: a return inside finally discards the one from the try, so the method answers finally and the exception, if there was one, disappears. That is a bug in every program that has it, which is why javac warns.
The hierarchy and multi-catch
Every exception extends Throwable, and the two branches are Exception for the ones a program handles and Error for the ones it cannot. RuntimeException is the unchecked branch of Exception. One catch may name several types when the body is the same:
public class Hierarchy {
public static void main(String[] args) {
for (String value : new String[] {"12", "x", null}) {
System.out.println(value + " -> " + parse(value));
}
System.out.println(effectivelyFinal());
}
static String parse(String value) {
try {
return String.valueOf(Integer.parseInt(value.strip()));
} catch (NumberFormatException | NullPointerException e) {
return "bad input: " + e.getClass().getSimpleName();
}
}
static int effectivelyFinal() {
try {
return 1;
} catch (RuntimeException e) {
return 2;
} finally {
System.out.println("cleanup");
}
}
}
javac -Xlint:all Hierarchy.java
java Hierarchy
12 -> 12
x -> bad input: NumberFormatException
null -> bad input: NullPointerException
cleanup
1
The two catches share a body because both mean "the input was not a number", and the multi-catch writes that once. The null case is worth a note: it used to throw NullPointerException from inside Integer.parseInt, and since Java 17 that call throws NumberFormatException instead; here the strip() is called first and the null is caught there.
The catch that comes too late
The catches are tried in order and the first one that matches handles the exception, so a broader catch before a narrower one makes the narrower one unreachable. The compiler refuses it rather than leaving dead code:
public class Order {
public static void main(String[] args) {
try {
throw new NumberFormatException("bad number");
} catch (Exception e) {
System.out.println("first catch gets it");
} catch (NumberFormatException e) {
System.out.println("never reached");
}
}
}
javac -Xlint:all Order.java
Order.java:7: error: exception NumberFormatException has already been caught
} catch (NumberFormatException e) {
^
1 error
The message is the rule: the earlier catch already covers the type. The fix is the order, from the most specific to the most general, which is also the order that makes the code say which case it thought about first.
The five rules
Catch the exception where something can be done about it, and let it travel otherwise. Never catch an exception and do nothing: an empty catch block is a promise that the failure does not matter, and it is almost never true. Do not catch Exception around a large block, because it hides the unchecked bugs of that block as well. Do not use an exception for an expected answer, which is the boolean of lesson 047 and the Optional of lesson 089. And do not put a return in a finally.
The next three lessons take the parts apart: writing your own exception and declaring it, the resource that closes itself, and the message and cause that make a failure readable.
Exercises
- Add a try that divides by zero and catch the unchecked exception it throws.
- Remove the catch from parse and declare the exception instead, then handle it in main.
- Make finallyWins answer from the try only and explain the warning that disappears.
- Catch RuntimeException before IllegalStateException and read the error.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which exception must a caller handle or declare?
Answer
A checked one, such as ClassNotFoundException
The compiler tracks checked exceptions through the throws clause of every method.
-
When does a finally block run?
Answer
On every path out of the try: normal end, return, throw or an uncaught exception
The block is the cleanup, so it runs whatever way the try is left.
-
Why does a return in finally cause a warning?
Answer
It discards the return of the try and any exception on the way out
The finally wins over the normal result, so the real outcome is lost.
-
What does this program print?
public class Q1 { public static void main(String[] args) { try { throw new IllegalStateException("x"); } catch (RuntimeException e) { System.out.println("caught " + e.getMessage()); } finally { System.out.println("done"); } } }Answer
caught x / done
The catch prints first and the finally runs after it, on the way out.
-
Which branch of Throwable does a program handle?
Answer
Exception, while Error is for failures the program cannot recover from
Errors such as OutOfMemoryError are outside the program control, which is lesson 102.
-
What is wrong with an empty catch block?
Answer
It claims the failure does not matter, which is rarely true
A swallowed exception leaves no trace, and the bug appears later with no cause.
-
What does this program print?
public class Q2 { public static void main(String[] args) { try { Integer.parseInt("x"); } catch (NumberFormatException e) { System.out.println("bad"); } finally { System.out.println("done"); } } }Answer
bad / done
The parse throws, the catch prints, and the finally runs on the way out.
-
What is the first line of the compiler output for this program?
public class Q3 { public static void main(String[] args) { try { throw new IllegalStateException("x"); } catch (RuntimeException e) { System.out.println("broad"); } catch (IllegalStateException e) { System.out.println("narrow"); } } }Answer
error: exception IllegalStateException has already been caught
The broader catch comes first, so the narrower one can never run.
-
What does this program print?
public class Q4 { public static void main(String[] args) { try { int[] a = new int[1]; a[1] = 5; } catch (ArrayIndexOutOfBoundsException e) { System.out.println(e.getMessage()); } } }Answer
Index 1 out of bounds for length 1
The message names the index that was used and the length of the array.
-
When should an exception be used instead of a return value?
Answer
When the method cannot do its job, not for an answer the caller expects
An expected case is a value; an exception is for the path the method cannot complete.
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