Monday 24 October 2016

Handling Exceptions

/***********************************************************************************

Aim: WAP to take arguments from command line and converts every argument to integer
     value and stores in an int array. For every argument divide 10 by the integer
     and display division. WAP that will handle all type of possible runtime errors.
***********************************************************************************/

import java.util.*;
import java.io.*;

class t
{
public static void main(String[] args)
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] a = new int[3];
int x = 10,i=0;
int div; boolean t=false; String tree;
do{
try
{ t=false;
for(i=0;i<args.length;i++)
{
a[i] = Integer.parseInt(args[i]);
div = x/a[i];
System.out.println("10/"+a[i]+"="+div);
}
}
catch(NumberFormatException nfe)
{
System.out.println("Error: Not an Integer");
System.out.println("Enter New No: ");
try
{
args[i] = br.readLine();
}
catch(IOException ioe)
{
System.out.println("IOError: "+ioe);
}
}
catch(ArrayIndexOutOfBoundsException ai)
{
System.out.println("Array Index Out Of Bound: "+i);
System.exit(0);
}
catch(ArithmeticException ae)
{
System.out.println("ArithmeticException: Denominator is 0");
System.out.println("Enter New No: ");
try
{
args[i] = br.readLine();
t=true;
}
catch(IOException ioe)
{
System.out.println("IOError: "+ioe);
}

}}while(t);

}
}

/**********************************************************************************/
output:
java$:java t 1 2 0
          10/1=10
          10/2=5
          ArithmeticException: Denominator is 0
          Enter New No:
          5
          10/1=10
          10/2=5
          10/5=2

java $; java t 1 2 0 8
           10/1=10
           10/2=5
            ArithmeticException: Denominator is 0
           Enter New No:
           2
           10/1=10
           10/2=5
           10/2=5
Array Index Out Of Bound: 3

java $: java t i 2 4
Error: Not an Integer
Enter New No:
0

java $ :javac t.java

java $: java t i 2 4
Error: Not an Integer
Enter New No:
0
ArithmeticException: Denominator is 0
Enter New No:
4
10/4=2
10/2=5
10/4=2

No comments:

Post a Comment