WAP using try catch block. User should enter two command line arguments. If only one argument is entered then exception should be caught. In case of two command line arguments, if fist is divided by second and if second command line argument is 0 then catch the appropriate exception.
Code:
class NewException extends Exception
{
String m;
NewException(String message)
{
m = message;
}
void printmsg()
{
System.out.println(m);
}
}
class S7P1_Exception
{
public static void main(String args[])
{
int num[] = new int[args.length];
try
{
if(args.length<2)
{
throw new NewException("Require atleast 2 command line arguments.");
}
for(int i=0; i<args.length; i++)
{
num[i] = Integer.parseInt(args[i]);
}
int a = (int)num[0];
int b = (int)num[1];
double div = a/b;
System.out.println("\nDivision successful. No exceptions found.\n"+a+"/"+b+" = "+div);
}
catch(NewException e)
{
System.out.println("\nException Caught: ");
e.printmsg();
}
catch(NumberFormatException e2)
{
System.out.println("\nException Caught: ");
System.out.println("Require Integer arguments.");
}
catch(ArithmeticException e3)
{
System.out.println("\nException Caught: ");
System.out.println("Division by Zero.");
}
}
}