What is exception propagation in Java?



If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack, this process is known as exception propagation.

Example

Here is code segment showing how to use multiple try/catch

statements. class ExceptionPropogation {
   public static void main(String args[]) {
      int a,b;
      try {
         a = Integer.parseInt(args[0]);
         b = Integer.parseInt(args[1]);
         int c = a/b;
         System.out.println(c);
      } catch(ArrayIndexOutOfBoundsException ex) {
         System.out.println("Please pass the args while running the program");
      } catch(NumberFormatException e) {
         System.out.println("String cannot be converted as integer");
      } catch(ArithmeticException e1) {
         System.out.println("Division by zero is impossible"); }finally {
         System.out.println("The program is terminated");
      }
   }
}

Output

Please pass the args while running the program
The program is terminated
Lakshmi Srinivas
Lakshmi Srinivas

Programmer / Analyst / Technician


Advertisements