Card 05/ 10
Exception Propagation Walkthrough: From throw to catch
Four methods, a failure at the bottom, a handler at the top, and what happens to everything between.
When an exception is thrown, each method without a matching catch is abandoned in turn, and the exception moves up to its caller until one of them handles it. Following one exception through four methods shows the process, and it is what makes a stack trace readable afterwards.
public static void main(String[] args) {
try {
runReport();
} catch (IOException e) {
System.out.println("handled: " + e.getMessage());
}
}
static void runReport() throws IOException { collect(); }
static void collect() throws IOException { read(); }
static void read() throws IOException { throw new IOException("disk full"); }What one throw does to four stack frames
read throws
The exception object is created, and it records the chain of method calls as it stands right now, four methods deep. That record is what a stack trace prints later, and it is made at new, not at the catch.
read has no handler, so its frame is discarded
There is no try in read, so nothing here can take it. The method does not return a value and does not run any further lines; its frame, the memory for that one call, is removed and the exception continues upwards.
collect and runReport do the same
Both declared throws IOException, which is a promise to the compiler rather than an instruction to the runtime. Neither has a catch, so both frames are discarded in turn. Every line after the failing call in each of them is skipped.
main has a matching catch
handled: disk fullThe catch type is IOException and the thrown object is one, so this handler takes it. The exception stops travelling and normal execution resumes at the first line inside the catch.
If nothing had matched
The exception would have left main, the thread, the path of execution running main, would end, and the default handler would print the captured stack trace to standard error. That trace is the list of frames from step one, in the order they were discarded.
The useful consequence: the top line of a stack trace is where it was thrown and the bottom is where the program started. Reading from the top tells you what failed; reading down tells you what was being attempted.
← → move through sections and cards