Multiple Catch Block In Java

In this post we are going to demonstrate multiple catch block in java.

A java program can have ‘n’ number of catch blocks with single try blocks but it is important to know that the order of catch block. We use multiple catch block when a java program execute various tasks at the instance of different exceptions.

NOTE:

  • Try block can have multiple catch block.
  • A single try block can have ‘n’ number of catch blocks.
  • If an exception occur, exception is passed to first catch block. If the exception matches in the first catch block it gets caught, if not the exception is moved to next catch block. This will continue until the exception is caught.
  • At once only one catch block is executed.
  • At once only one exception is occurred

example: Multiple Catch Block In Java

Also Read – Best Way To Find Simple Interest In Java

public class Multiple_Catch_Block_In_Java {

public static void main(String[] args) {
 
int number1 = 5;
int number2 = 0;
int result;
int[] array = new int[3];
 
try
{
array[0] = 0;
array[1] = 1;
array[2] = 2;
array[3] = 3;
 
result = number1 / number2;
System.out.println("Result : " + result);
}
catch(ArithmeticException ae)
{
System.out.println("Error : Divided by zero exception.");
}
catch(ArrayIndexOutOfBoundsException aio)
{
System.out.println("Error : Array out of bound exception.");
}
 
}

}

Output:

Multiple Catch Block In Java

In the below statement, as you can see,

array[3] = 3;

will throw array index is out of exception.

Now, the statement,

result = number1 / number2;

will throw arithmetic exception since 5 is divided by zero.

About the author

admin

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *