Essay
Learning Java, Part 9: Exception Handling
Study notes on the Throwable hierarchy, try and catch, what an uncaught exception does, multiple and multi-catch blocks, ordering catches, throw and rethrow, finally, checked versus unchecked exceptions and throws, chained exceptions, and writing your own exception classes. Written entirely by an AI model.
Part 5 of the Python series introduced try and except. Java’s version works the same way at runtime. The big difference is at compile time: for some exceptions, the compiler forces you to deal with them.
The exception hierarchy
Every exception is an object whose class descends from Throwable:
Throwable
├── Error serious JVM problems: don't catch
│ ├── OutOfMemoryError
│ └── StackOverflowError
└── Exception problems a program can handle
├── IOException checked
│ └── FileNotFoundException
├── InterruptedException checked
└── RuntimeException unchecked
├── ArithmeticException
├── NullPointerException
├── IllegalArgumentException
│ └── NumberFormatException
├── IllegalStateException
├── ClassCastException
└── IndexOutOfBoundsException
└── ArrayIndexOutOfBoundsException
try and catch
public class Split {
public static void main(String[] args) {
int[] bills = {120, 90};
int[] people = {4, 0};
for (int i = 0; i < bills.length; i++) {
try {
System.out.println(bills[i] / people[i]);
} catch (ArithmeticException e) {
System.out.println("no one to split with: " + e.getMessage());
}
}
System.out.println("done");
}
}
30
no one to split with: / by zero
done
When an exception is thrown, Java abandons the rest of the try block and looks for a matching catch. After the catch runs, execution continues after the whole try statement, not back where the exception happened.
An uncaught exception
If nothing catches an exception, it travels back up the call stack, ending each method on the way. If it leaves main, the program stops and the JVM prints the exception and a stack trace:
public class Crash {
static int first(int[] a) { return a[0]; }
public static void main(String[] args) {
System.out.println(first(new int[0]));
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at Crash.first(Crash.java:2)
at Crash.main(Crash.java:4)
Read a stack trace from the top: the first line is what went wrong, and the first at line is where. The lines below show who called whom.
Several catches
A try may have several catch blocks, tried in order. The first whose type matches (including by inheritance) wins:
public class Parse {
static int parseCups(String s) {
try {
int n = Integer.parseInt(s);
return 12 / n;
} catch (NumberFormatException e) {
System.out.println("not a number: " + s);
} catch (ArithmeticException e) {
System.out.println("zero cups");
} catch (RuntimeException e) {
System.out.println("something else: " + e);
}
return -1;
}
public static void main(String[] args) {
System.out.println(parseCups("3"));
parseCups("three");
parseCups("0");
}
}
4
not a number: three
zero cups
- A superclass catch must come after its subclasses. Putting
catch (RuntimeException e)first makes the later ones unreachable, and that is a compile error. - Multi-catch handles unrelated types in one block:
catch (NumberFormatException | ArithmeticException e). - Catching
Exceptioneverywhere hides bugs. Catch the specific exception you expect, as the Python notes also advised. - Try statements can be nested; an exception the inner one doesn’t catch goes to the outer one.
throw
throw raises an exception. Use it to reject bad input at the start of a method:
public class Throw {
static double sqrtOf(double x) {
if (x < 0) throw new IllegalArgumentException("negative: " + x);
return Math.sqrt(x);
}
public static void main(String[] args) {
System.out.println(sqrtOf(9));
try {
sqrtOf(-1);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
3.0
negative: -1.0
A catch block can also rethrow: throw e; passes the same exception on after, say, logging it.
finally
A finally block runs whether the try finished normally, threw, or returned. Use it for clean-up:
public class Finally {
static String brew(boolean fail) {
try {
if (fail) throw new IllegalStateException("no water");
return "tea";
} catch (IllegalStateException e) {
return "error: " + e.getMessage();
} finally {
System.out.println("kettle off");
}
}
public static void main(String[] args) {
System.out.println(brew(false));
System.out.println(brew(true));
}
}
kettle off
tea
kettle off
error: no water
Even with return in the try, finally runs before the method actually returns. Do not put return in a finally block: it overrides the earlier return and silently swallows any exception. For files and other resources, try-with-resources (Part 10) is better than finally.
Checked and unchecked exceptions
- Unchecked exceptions are
RuntimeException,Errorand their subclasses. They usually mean a bug (a null reference, a bad index) and the compiler does not track them. - Checked exceptions are every other
Exception, such asIOException. They describe failures a correct program must still expect: a missing file, a dropped network connection.
For a checked exception, the compiler enforces catch or declare: a method that might throw one must either catch it or say so with throws in its header.
import java.io.IOException;
public class Throws {
static String readConfig(boolean exists) throws IOException {
if (!exists) throw new IOException("config missing");
return "ok";
}
public static void main(String[] args) {
try {
System.out.println(readConfig(true));
System.out.println(readConfig(false));
} catch (IOException e) {
System.out.println("caught " + e.getMessage());
}
}
}
ok
caught config missing
Remove the try in main and the program does not compile: “unreported exception IOException; must be caught or declared to be thrown”. Python has no such rule. An overriding method may not declare broader checked exceptions than the method it overrides.
A closer look at Throwable
Useful methods on any exception: getMessage() (the text), toString() (class and message), printStackTrace() (the full trace) and getCause().
Chained exceptions wrap a low-level cause inside a higher-level one, so the original detail is not lost:
public class Chain {
static int loadPrice(String raw) {
try {
return Integer.parseInt(raw);
} catch (NumberFormatException e) {
throw new IllegalStateException("bad price file", e); // keep the cause
}
}
public static void main(String[] args) {
try {
loadPrice("4.50");
} catch (IllegalStateException e) {
System.out.println(e.getMessage() + " <- " + e.getCause().getMessage());
}
}
}
bad price file <- For input string: "4.50"
Your own exceptions
Extend Exception for a checked exception or RuntimeException for an unchecked one. Give it constructors that pass a message (and optionally a cause) to super:
class InsufficientFundsException extends Exception {
private final long shortBy;
InsufficientFundsException(long shortBy) {
super("short by " + shortBy + " cents");
this.shortBy = shortBy;
}
long shortBy() { return shortBy; }
}
class Wallet {
private long cents = 1000;
void pay(long amount) throws InsufficientFundsException {
if (amount > cents) throw new InsufficientFundsException(amount - cents);
cents -= amount;
}
}
public class Custom {
public static void main(String[] args) {
Wallet w = new Wallet();
try {
w.pay(600);
w.pay(600);
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage() + " (" + e.shortBy() + ")");
}
}
}
short by 200 cents (200)
Which to choose: make it checked if a caller can reasonably recover (pay with another card), and unchecked if it means the caller made a programming error (passing a negative amount).
Exam-style checks
- Explain the difference between checked and unchecked exceptions, with one example of each.
- What does “catch or declare” mean? Show both ways of satisfying it.
- Why must
catch (Exception e)come aftercatch (IOException e)? - When does a
finallyblock run? What goes wrong if it contains areturn? - Write a custom exception class and a method that throws it.
Where to practise
Schildt’s Chapter 9 adds QueueFullException and QueueEmptyException to the queue from earlier parts. Do the same with your own queue, then write a program that reads integers with a Scanner and keeps asking until valid input arrives, catching InputMismatchException (and discarding the bad token with next()).