Exception Propagation: How Exceptions Move Up the Call Stack
What you'll learn: How thrown exceptions automatically travel upward through method calls until something catches them.
The Core Concept
When you throw an exception inside a method and that method doesn't catch it, the exception doesn't just disappear. It propagates (moves) up the call stack to the method that called it. If that method doesn't catch it either, the exception continues upward, method by method, until either something catches it or it reaches main(). If even main() doesn't handle it, your program terminates with an error message.
Think of it like passing a hot potato upward through a chain of hands—each method has a chance to catch (handle) it, but if they don't, they automatically pass it to whoever called them.
How It Works
public class PropagationDemo {
public static void main(String[] args) {
try {
methodA();
} catch (ArithmeticException e) {
System.out.println("Caught in main: " + e.getMessage());
}
}
static void methodA() {
methodB(); // methodA doesn't catch, so exception propagates through
}
static void methodB() {
methodC(); // methodB doesn't catch either
}
static void methodC() {
int result = 10 / 0; // Exception thrown here!
// propagates: methodC → methodB → methodA → main → CAUGHT!
}
}
The ArithmeticException originates in methodC, but since none of the intermediate methods have try-catch blocks, it automatically bubbles up until main() catches it.
Key Takeaway: Exceptions propagate automatically up the call stack through each calling method until caught or until the program terminates—you don't need explicit code to pass them upward.