Saturday 25 December 2021

Multi catch statements in java

It is possible to have more than one catch statement in the catch block as given below.

try

{

statements;

}ctach(Exception-type1 ex)

{

statements;

}catch(Exception-type2 ex)

{

statements;

}catch(Exception-type3 ex)

When an exception in a try block is generated, the java consider the multi catch statement like case statement in switch statement. The first statement whose parameter matches with the exception object will be executed and the remaining statement will be skipped.

class JavaErrorDemo2 
{
	public static void main(String[] args) 
	{
		int a[]={5,10},b=5;
		int x,y;
		try
		{
		  x=a[2]/(b-a[1]);	
		}
		catch(ArithmeticException ex)
		{
			System.out.println("Division by zero");
		}
		catch(ArrayIndexOutOfBoundsException ex)
		{
			System.out.println("Array Index error");
		}
		catch(ArrayStoreException ex)
		{
			System.out.println("Wrong data type");
		}
		y=a[1]/a[0];
		System.out.println("Value of Y is="+ y);
	}
}

Output

D:\java examples>javac JavaErrorDemo2.java
D:\java examples>java JavaErrorDemo2
Array Index error
Value of Y is=2

In the above program, we are trying to access the array values out of index, it will generate an exception and that is caught in the catch block then it is handled.

0 comments :

Post a Comment

Note: only a member of this blog may post a comment.

Machine Learning

More

Advertisement

Java Tutorial

More

UGC NET CS TUTORIAL

MFCS
COA
PL-CG
DBMS
OPERATING SYSTEM
SOFTWARE ENG
DSA
TOC-CD
ARTIFICIAL INT

C Programming

More

Python Tutorial

More

Data Structures

More

computer Organization

More
Top