A method sometimes cannot do its job: an array index is out of range, a file is missing, an integer is divided by zero. Java then creates an exception object and throws it, and the method stops at that line. If the method does not handle the exception (the next section shows how), it goes to the caller, then to its caller, and so on. Every running call has a frame on the call stack, and each frame is removed as the exception passes. This is called unwinding.
Here main calls a, a calls b, b calls c, and c fails. All code in this chapter is Java 17.
public class Demo {
static void c() { int[] v = new int[2]; v[5] = 1; }
static void b() { c(); }
static void a() { b(); }
public static void main(String[] args) { a(); }
}
// Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
// Index 5 out of bounds for length 2
// then one "at" line each for c, b, a and main
Nothing handles it, so every frame is removed and the program ends with a stack trace.
UNWINDING THE CALL STACK
throw in c⇒pop c→pop b→pop a→pop main
Holds when no method on the way handles the exception, as in Demo. Popping a frame abandons the rest of that method's lines. The next section shows how a matching catch stops the unwinding at its frame. If nothing handles it, main's frame goes too, and the program stops and prints the stack trace.
Every thrown object belongs to a class tree. The top class is Throwable. Under it sit Error, for serious failures such as running out of memory that a program should not try to handle, and Exception, for problems a program can reasonably handle. The compiler also sorts these classes into checked and unchecked. A method that can let a checked exception escape must say so with throws and the class name in its header, as in void load() throws IOException.
THE THROWABLE HIERARCHY IN OUTLINE
Throwable⊃Error,Throwable⊃Exception⊃RuntimeException
The symbol A⊃B means A is a superclass of B. Only objects of Throwable or its subclasses can be thrown or caught. RuntimeException extends Exception, yet it is unchecked, as the table shows.