Handle the following exceptions using exception handling mechanism in java. (Note: Handle all exceptions in single program using command line arguments) a. ArithmeticException b. ArrayIndexOutOfBoundsException c. NullPointerException d. IOException e. NumberFormatException

 /* To Handle all exceptions in single program

using command line arguments */

import java.util.*;
import java.lang.*;
class ExceptionHandling_5A
{
    public static void main(String args[])
    {
    try
    {
      int a,c,d,x;  
     
      // ArithmeticException  
      a = Integer.parseInt(args[0]);
      x = 36/a;
      System.out.println("Division result is : "+x);
     
      // ArrayIndexOutOfBoundsException
      int b[] = new int[10];
      b[a] = Integer.parseInt(args[1]);
      System.out.println("Element in array : "+b[a]);

      // NumberFormatException
      c = Integer.parseInt(args[2]);
      System.out.println("Given number is : " +c);

      // StringIndexOutOfBoundsException
      System.out.println("Charecter at 5th index is : "+args[3].charAt(5));

      // NullPointerException
      if(args[3].length() < 10)
      {    
        String s = null;
        System.out.println("Length of string is : " +s.length());
      }
      else
      {
        System.out.println("Given string is : " +args[3]);
      }
    }
    catch(ArithmeticException e1)
    {
        System.out.println(e1);
    }
    catch(ArrayIndexOutOfBoundsException e2)
    {
        System.out.println(e2);
    }
    catch(NumberFormatException e3)
    {
        System.out.println(e3);
    }
    catch(StringIndexOutOfBoundsException e4)
    {
        System.out.println(e4);
    }  
    catch(NullPointerException e5)
    {
        System.out.println(e5);
    }
    }
}


Comments

Popular posts from this blog

Design GUI to handle Choice Control event.

Write a Java program that reads an integer number (between 1 and 255) from the user and prints the binary representation of the number. The answer should be printed as a String. Note: The output displayed should contain 8 digits and should be padded with leading 0s(zeros), in case the returned String contains less than 8 characters. For example, if the user enters the value 16, then the output should be 00010000 and if the user enters the value 100, the output should be 01100100 (Hint : You may use String.format() method for the expected output)