Sunday, 12 March 2023

8. Write a program which takes the age of 5 persons from command line and find the average age of all persons. The program should handle exception if the argument is not correctly formatted and custom exception if the age is not between 1 to 100.



class RangeException extends Exception
{
    RangeException(int a)
    {
        System.out.println("\nage is not valid because not uner 1 to 100");
    }
}

class Program8
{
    public static void main(String args[])
    {
        int arr[] = new int[5];
       
        try
        {
            for(int i=0; i<5; i++)
            {
                arr[i] = Integer.parseInt(args[i]);
                if(arr[i] > 100 || arr[i] < 1)
                    throw new RangeException(arr[i]);
            }
        }
        catch(ArrayIndexOutOfBoundsException e)
             {
                 System.out.println(e.getMessage());
             }
             catch(NumberFormatException n)
             {
                 System.out.println(n.getMessage());
             }
             catch(ArithmeticException a)
             {
                 System.out.println(a.getMessage());
             }
             catch(Exception e)
             {
                 System.out.println(e.getMessage());
             }
    }
}


No comments:

Post a Comment

python programs

1. sum of two number