Exception Handling : Multiple Catch


 

Exception Handling : Multiple Catch

In this tutorial, we will discuss the use of declaring multiple catch with the try block.

In this tutorial, we will discuss the use of declaring multiple catch with the try block.

Exception Handling : Multiple Catch

In this tutorial, we will discuss the use of declaring multiple catch  with the try block.

Multiple Catch : A try statement can have multiple catch blocks. Through multiple catch with the same try block, you can raise different types of exceptions. When an exception is thrown, it traverse through the catch blocks to find the matching catch block. It is having one limitation as it generate unreachable code error. If the first catch block contains the Exception class object then the other catch blocks are never executed.

 Example :

class MultipleCatch {
public static void main(String[] args) {
int[] array = { 2, 3 };
int n1, n2, result;
n1 = 20;
n2 = 0;
try {
System.out.println("n1/array[2] = " + n1 / array[2]);
result = n1 / n2;
} catch (ArithmeticException e) {
System.out.println(e);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}
}
}

Description : In this example, we have defined two catch blocks to handle two different exception with same try block. In the code, we have defined two statements that may raise the exceptions  ArrayIndexOutOfBoundsException and ArithmeticException respectively. These statements are kept under the try block. When the program is executed, an exception will be raised. Though both the statements will throw an exception, but priority lies with the first statement, if it throws exception, then it will executed skipping the other statement. It the first statement is correct, then  the first catch block will be skipped and the second catch block handles the error.

Output :

java.lang.ArrayIndexOutOfBoundsException: 2

Ads