Exception propagation in Java

Java 8Object Oriented ProgrammingProgramming

Exception propagation in Java occurs when an exception thrown from the top of the stack. When it is not caught, the exception drops down the call stack of the preceding method. If it is not caught there, it further drops down to the previous method. This continues until the method reaches the bottom of the call stack or is caught somewhere in between.

Example

Let us see an example which illustrates exception propagation in Java −

 Live Demo

public class Example {
   void method1() // generates an exception {
      int arr[] = {10,20,30};
      System.out.println(arr[7]);
   }
   void method2() // doesn't catch the exception {
      method1();
   }
   // method1 drops down the call stack
   void method3() // method3 catches the exception {
      try {
         method2();
      } catch(ArrayIndexOutOfBoundsException ae) {
         System.out.println("Exception is caught");
      }
   }
   public static void main(String args[]) {
      Example obj = new Example();
      obj.method3();
   }
}

Output

The output is as follows −

Exception is caught
raja
Published on 03-Jan-2019 10:02:04
Advertisements