Multi-catch in Java



An exception is an issue (run time error) that occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed.

Multiple exceptions in a code

Before Java 7 whenever we have a code that may generate more than one exception and if you need to handle them specifically you are supposed to use multiple catch blocks on a single try.

Multicatch block

From Java 7 onwards a Multi-catch block is introduced using this, you can handle more than one exception within a single catch block.

In this, you need to specify all the exception classes to be handled separated by “ | ” as shown below −

catch(ArrayIndexOutOfBoundsException | ArithmeticException exp) {
   System.out.println("Warning: Enter inputs as per instructions ");
}

Example

The following Java program demonstrates the usage of Multi-catch. Here we are handling all the exceptions in a single catch block.

 Live Demo

import java.util.Arrays;
import java.util.Scanner;
public class MultiCatch {
   public static void main(String [] args) {
      Scanner sc = new Scanner(System.in);
      int[] arr = {10, 20, 30, 2, 0, 8};
      System.out.println("Array: "+Arrays.toString(arr));
      System.out.println("Choose numerator and denominator(not 0) from this array, (enter positions 0 to 5)");
      int a = sc.nextInt();
      int b = sc.nextInt();
      try {
         int result = (arr[a])/(arr[b]);
         System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
      }
      catch(ArrayIndexOutOfBoundsException | ArithmeticException exp) {
         System.out.println("Warning: Enter inputs as per instructions ");
      }
   }
}

Output1

Enter 3 integer values one by one:
Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator (not 0) from this array, (enter positions 0 to 5)
0
9
Warning: Enter inputs as per instructions

Output2

Enter 3 integer values one by one:
Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator (not 0) from this array, (enter positions 0 to 5)
2
4
Warning: Enter inputs as per instructions

Advertisements