Multiple catch blocks: Several types of exceptions may arise when executing the program. They can be handled by using multiple catch blocks for the same try block. In such cases, when an exception occurs the run time system will try to find match for the exception object with the parameters of the catch blocks in the order of appearance. When a match is found the corresponding catch block will be executed. If there is no matching catch block the program will be terminated abruptly. Multiple catch blocks are necessary because handling code is different for different types of errors.
class Test
{
public static void main(String as[])
{
try
{
int x=Integer.parseInt(as[0]);
int y=Integer.parseInt(as[1]);
System.out.print("Division="+ (x/y));
}
catch(ArithmeticException ae)
{
System.out.println("Denominator was zero");
}
catch(NumberFormatException ne)
{
System.out.println("Please supply numbers");
}
catch(ArrayIndexOutOfBoundsException ie)
{
System.out.println("Please supply two arguments");
}
}
}
The above program produces the following output in different runs.
c:\jdk1.5\bin>java Test 8 0
Denominator was zero
c:\jdk1.5\bin>java Test xx yy
Please supply numbers
c:\jdk1.5\bin>java Test 5
Please supply two arguments
0 comments:
Post a Comment