Mark As Completed Discussion

Exception Propagation

In Java, exception propagation refers to the process of transferring an exception from the place where it occurred to a higher-level method that can handle it. When an exception is thrown and not caught within a method, it is propagated up the call stack to the nearest enclosing try-catch block or to the JVM if no appropriate catch block is found.

Let's consider an example to understand exception propagation:

TEXT/X-JAVA
1class Main {
2   public static void main(String[] args) {
3       try {
4           divideByZero();
5       } catch (ArithmeticException e) {
6           System.out.println("Exception caught: " + e.getMessage());
7       }
8   }
9   
10   public static void divideByZero() {
11       int num = 10;
12       int result = num / 0;
13       System.out.println(result);
14   }
15}

In this example, the divideByZero method attempts to perform a division by zero, which throws an ArithmeticException. Since the exception is not caught within the divideByZero method, it is propagated up the call stack to the main method, where it is caught and handled within the try-catch block.

When running the above code, the following output will be displayed:

SNIPPET
1Exception caught: / by zero
JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment