It is
possible to use multiple catch blocks with a single try block as shown below:
……..
……..
try
{
statement;
}
catch(Exception-Type-1 e)
{
statement;
}
catch(Exception-Type-2 e)
{
statement;
}
……..
catch(Exception-Type-N e)
{
statement;
}
When an
exception occurs in a try block,
Java treats the multiple catch statements like cases in a switch statement. The
first catch statement whose parameters match with the exception object will be executed
and the remaining statements will be skipped.
Example:
classMulticatch
{
public
static void main(String args[])
{
int
a[]={10,20},r;
try
{
r=a[2]/(a[1]-20);
}
catch(ArithmeticException
e)
{
System.out.println("Arithmetic
exception occurred");
}
catch(ArrayIndexOutOfBoundsException
e)
{
System.out.println("Array
indexing exception occurred");
}
r=a[0]+a[1];
System.out.println("Result
= "+r);
}
}
Output:
Array indexing
exception occurred
Result = 30
No comments:
Write comments