Propagation with No Matching catch Block
What you'll learn: You'll discover what happens when an exception travels through the call stack without finding any catch block to handle it.
The Unhandled Exception Journey
When you throw an exception (either manually with throw or automatically by the JVM), Java searches for a matching catch block in the current method. If none exists, the exception propagates up to the calling method. This process continues up the call stack—but what if no method catches it?
The program terminates.
When an exception reaches the top of the call stack without being caught anywhere, the JVM steps in and aborts your program. It prints a stack trace showing where the exception originated and the path it traveled, then exits.
How It Works
Imagine a relay race where runners pass a baton (the exception). Each runner (method) can choose to handle it (catch it) or pass it along (propagate it). If the baton reaches the end with no one willing to handle it, the race is called off—your program stops.
public class UnhandledExample {
public static void main(String[] args) {
methodA();
System.out.println("This never prints");
}
static void methodA() {
methodB();
}
static void methodB() {
throw new RuntimeException("Oops!");
}
}
When methodB() throws the exception, it propagates to methodA(), then to main(). Since none of these methods have a catch block for RuntimeException, the JVM terminates the program and prints a stack trace showing: RuntimeException at methodB, called from methodA, called from main.
The line "This never prints" never executes—program flow stops immediately when the exception exits main() unhandled.
Key Takeaway: When an exception propagates through all methods without finding a matching catch block, the JVM terminates the program and displays a stack trace showing where the exception occurred and how it traveled up the call stack.