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 May 3, 2021 in JAVA by Robindeniel
0 votes
asked Oct 27, 2020 in JAVA by sharadyadav1986
0 votes
asked Dec 6, 2020 in JAVA by rajeshsharma
0 votes
asked May 7, 2021 in JAVA by sharadyadav1986
...