Can a try block have multiple catch blocks in Java?



Yes, you can have multiple catch blocks for a single try block.

Example

The following Java program contains an array of numbers (which is displayed). from user it accepts two positions from this array and, divides the number in first position with the number in second position.

While entering values −

  • If you choose a position which is not in the displayed array an ArrayIndexOutOfBoundsException is thrown

  • If you choose 0 as denominator and ArithmeticException is thrown.

In this program we have handled all the possible exceptions using two different catch blocks.

 Live Demo

import java.util.Arrays;
import java.util.Scanner;
public class MultipleCatchBlocks {
   public static void main(String [] args) {
      Scanner sc = new Scanner(System.in);
      int[] arr = {10, 20, 30, 2, 0, 8};
      System.out.println("Enter 3 integer values one by one: ");
      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 e) {
         System.out.println("Warning: You have chosen a position which is not in the array");
      }
      catch(ArithmeticException e) {
         System.out.println("Warning: You cannot divide an number with 0");
      }
   }
}

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)
2
8
Warning: You have chosen a position which is not in the array

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)
1
4
Warning: You cannot divide an number with 0

Advertisements