Home » Java programming language

Handling Multiple Catch Clauses in Java

Learn: In this article, we will see how to use more than one catch blocks in a single try block?
Submitted by Abhishek Jain, on September 05, 2017

So far we have seen how to use a single catch block, now we will see how to use more than one catch blocks in a single try block.

In java, when we handle more than one exceptions within a single try {} block then we can use multiple catch blocks to handle many different kind of exceptions that may be generated while running the program. However every catch block can handle only one type of exception. This mechanism is necessary when the try block has statement that raises different type of exceptions.

The syntax for using multiple catch clause is given below:

try{
	???
	???
}
catch(<exceptionclass_1><obj1>){
	//statements to handle the
	exception
}
catch(<exceptionclass_2><obj2>){
	//statements to handle the
	exception
}
catch(<exceptionclass_N><objN>){
	//statements to handle the
	exception 
}

When an exception is thrown, normal execution is suspended. The runtime system proceeds to find a matching catch block that can handle the exception. If no handler is found, then the exception is dealt with by the default exception handler at the top level.

Let’s see an example given below which shows the implementation of multiple catch blocks for a single try block.

public class Multi_Catch
{
	public static void main(String args[])
	{
		int array[]={20,10,30};
		int num1=15,num2=0;
		int res=0;

		try
		{
			res = num1/num2;
			System.out.println("The result is" +res);
			for(int ct =2;ct >=0; ct--)
			{
				System.out.println("The value of array are" +array[ct]);
			}
		}
		catch (ArrayIndexOutOfBoundsException e)
		{
			System.out.println("Error?. Array is out of Bounds");
		}
		catch (ArithmeticException e)
		{
			System.out.println ("Can't be divided by Zero");
		} 
	} 
}

In this example, ArrayIndexOutOfBoundsExceptionand ArithmeticExceptionare two catch clauses we have used forcatching the exception in which the statements that may cause exception are kept within the try block. When the program is executed, an exception will be raised. Now that time the first catch block is skipped and the second catch block handles the error.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.