-2

I was trying to catch multiple exceptions, but I could not. I was only able to catch one exception.

class Main {
  public static void main(String[] args) {
    try {
      int array[] = new int[10];
      array[10] = 30 / 0;
    } catch (ArithmeticException e) {
      System.out.println(e.getMessage());
    } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println(e.getMessage());
    }
  }
}
  • https://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html This has existed for some time; searching the web works too. – Dave Newton Jun 27 '21 at 02:38
  • 2
    What multiple exceptions? When the division-by-zero error occurs, the code in the `try` block stops executing, so it never reaches the code that would otherwise cause index-out-of-bounds error. – Andreas Jun 27 '21 at 02:39
  • There can only be one exception at a time not more than that, as when exception occurs it moves to the catch block – Ashish Mishra Jun 27 '21 at 02:43

1 Answers1

1

As in the statements array[10] = 30 / 0; you can see what the compiler will do at the first hand is evaluation of 30 divide by zero that will surely throw a arithmetic exception. As a statement before assigning operation throws exception thus it will break from the try block and skip to catch (ArithmeticException e) block , array[invalidIndex] is never executed so it will never throw ArrayIndexOutOfBoundsException.

Ashish Mishra
  • 704
  • 1
  • 6
  • 20