Exception Propagation in Java
Problem
An exception thrown deep inside a call chain doesn't stop at the method that threw it — it keeps unwinding through every calling method, skipping each one entirely, until it reaches a try-catch that matches it or the program crashes.
Throw an exception in a method several calls deep, with no catch anywhere except at the very top, and confirm it's still handled correctly there.
Java Program
public class ExceptionPropagationExample {
static void methodC() {
int[] arr = new int[3];
System.out.println(arr[5]); // throws here, with no local try-catch
}
static void methodB() {
methodC();
}
static void methodA() {
methodB();
}
public static void main(String[] args) {
try {
methodA();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught in main: " + e.getMessage());
}
}
}Output
Core Logic
None of the intermediate methods have a try-catch of their own, so the exception simply exits each one in turn — unwinding the call stack — until it reaches the one method that does catch it.
- 1
methodC()accessesarr[5]on a 3-element array, throwing anArrayIndexOutOfBoundsException. - 2
methodB()calledmethodC()with no try-catch around it, so the exception exitsmethodB()immediately, withoutmethodB()ever getting a chance to react. - 3
methodA()calledmethodB(), also with no try-catch, so the same thing happens again — the exception passes straight through. - 4
main()is the only method with a try-catch around its call, so that's where the exception finally stops and gets handled.
methodC() but is only ever caught in main(), three calls up — every method in between contributes nothing to handling it.Key Point: None of the intermediate methods need to know or care that an exception might occur — propagation happens automatically, which is exactly why a try-catch doesn't have to sit at every single call site.