English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Exception propagation in Java programming

Exception propagation refers to the flow of exceptions from one catch block to another. The following are the rules-

  • If an exception occurs in protected code, then the exception is thrown to the first catch block in the list.

  • If the data type of the thrown exception is the same as ExceptionType1If it matches, it will be caught here.

  • If not, the exception is passed to the second catch statement.

  • This continues until the exception is caught or falls through all the catches.

  • In the final case, the current method stops executing, and the exception is discarded to the previous method in the call stack, this process is called exception propagation.

Example

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 Result

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