The following program demonstrates exception handling. If zero is supplied for the second argument through command line, the code attempts to divide the first value with zero which raises a runtime error. But, as we have used exception handling mechanism here with appropriate catch block, the exception will be caught and the program will not be abruptly terminated.
class Test
{
public static void main(String as[])
{
int a=Integer.parseInt(as[0]);
int b=Integer.parseInt(as[1]);
try
{
System.out.println(“Division=”+ (a/b));
}
catch(ArithmeticException e)
{
System.out.println("Please check the Denominator”);
System.out.println(e);
}
}
}
The above program produces the following output.
Output 1: (No Exception)
D:\java>java Test 6 2
Division =3
Division =3
Output 2: (With Exception)
D:\java>java Test 6 0
Please check the Denominator
java.lang.ArithmeticException: / by zeroPlease check the Denominator
0 comments:
Post a Comment