Chapter 6 · Simulation

Exception Flow

← Chapter 6
Java code
    Call stack
    Output (console)

    Exception Flow

    Goal: see which lines are skipped when an exception is thrown, which methods the exception passes through as it propagates along the call stack, and in what order the try, catch and finally blocks run.

    How to use it

    1. Choose a scenario and a value or version on the left. Step ▶ / ◀ Back (keyboard → / ←), Play, Reset.
    2. In the code in the middle the current line is highlighted; the red line is where the exception is thrown. On the right the stack grows from bottom to top; each frame shows which block (try, catch, finally) the method is in. A frame with a dashed outline is a method that is about to be thrown off the stack because of the exception.
    3. With What is the output? on, you look at the candidates A, B and C before the program runs and choose the correct output.

    Rules

    • When an exception is thrown, the remaining lines of that block do not run. The JVM searches from the inside out for the first catch block whose type matches; every method that has none is thrown off the stack.
    • finally runs in every case: when the block ends normally, when it is left with return, and when an exception passes through uncaught.
    • catch blocks are tried from top to bottom; a subclass must be written before its superclass, otherwise it is a compile error.
    • Checked exceptions (such as IOException) must either be caught or declared with throws; the compiler enforces this. Subclasses of RuntimeException are unchecked exceptions.
    • An exception that is caught nowhere is caught by the JVM, which writes the stack trace to the standard error stream and terminates the program.
    • try-with-resources closes the resources in the reverse of the order they were opened; closing happens before the catch and finally blocks.

    Every version of every scenario was compiled with javac --release 8 and run on Java 8 and Java 21; the outputs shown, the stack trace line numbers and the compiler messages are taken from those runs.

    Related slides: Chapter 6 · Exceptions (try-catch Flow, finally and return, try-with-resources, Checked Exceptions, Propagation).