Exception propagation in Java programming



Exception propagation refers to flows of exception from one catch block to other. Following are the rules −

  • 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.

  • At end 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

 Live Demo

public class Tester {
   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

Advertisements