Slip No 29 Q A

Q.Write a java program to check whether given candidate is eligible for voting or not. Handle user defined as well as system defined Exception. [15 M]

import java.util.Scanner;

// User-defined Exception
class AgeNotValidException extends Exception
{
    public AgeNotValidException(String msg)
    {
        super(msg);
    }
}

public class VotingEligibility
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);

        try
        {
            System.out.print("Enter Age: ");
            String input = sc.nextLine();

            int age = Integer.parseInt(input);   // System-defined Exception

            if(age < 18)
            {
                throw new AgeNotValidException("Candidate is not eligible for voting.");
            }
            else
            {
                System.out.println("Candidate is eligible for voting.");
            }
        }
        catch(NumberFormatException e)
        {
            System.out.println("Invalid input! Please enter numeric age.");
        }
        catch(AgeNotValidException e)
        {
            System.out.println(e.getMessage());
        }
        finally
        {
            System.out.println("Program Ended.");
        }

        sc.close();
    }
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top