Share on Google+Share on Google+

Exception Handling : Multiple Catch

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) {
} catch (ArrayIndexOutOfBoundsException 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


Posted on: November 21, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.