Java ProgramsExceptionsException Propagation

Exception Propagation in Java

intermediate·  Exceptions  ·  Error Handling

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.

Input
main() calls methodA() calls methodB() calls methodC(), which throws
Output
Caught in main: Index 5 out of bounds for length 3

Java Program

Java
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

Caught in main: Index 5 out of bounds for length 3

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.

How It Works
  1. 1methodC() accesses arr[5] on a 3-element array, throwing an ArrayIndexOutOfBoundsException.
  2. 2methodB() called methodC() with no try-catch around it, so the exception exits methodB() immediately, without methodB() ever getting a chance to react.
  3. 3methodA() called methodB(), also with no try-catch, so the same thing happens again — the exception passes straight through.
  4. 4main() is the only method with a try-catch around its call, so that's where the exception finally stops and gets handled.
The exception originates in 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.

Key Concepts

call stackunwindingtry / catch

Related Programs