0 votes
in JAVA by
A single try block and multiple catch blocks can co-exist in a Java Program. Explain.

1 Answer

0 votes
by
Yes, multiple catch blocks can exist but specific approaches should come prior to the general approach because only the first catch block satisfying the catch condition is executed. The given code illustrates the same:

public class MultipleCatch {

public static void main(String args[]) {

try {

int n = 1000, x = 0;

int arr[] = new int[n];

for (int i = 0; i <= n; i++) {

arr[i] = i / x;

}

}

catch (ArrayIndexOutOfBoundsException exception) {

System.out.println("1st block = ArrayIndexOutOfBoundsException");

}

catch (ArithmeticException exception) {

System.out.println("2nd block = ArithmeticException");

}

catch (Exception exception) {

System.out.println("3rd block = Exception");

}

}

}

Here, the second catch block will be executed because of division by 0 (i / x). Incase x was greater than 0 then the first catch block will execute because for loop runs till i = n and array index are till n-1.

Related questions

0 votes
asked Nov 2, 2023 in ReactJS by AdilsonLima
0 votes
asked Oct 18, 2019 in C Sharp by Robin
...