Monday, 6 November 2023

Write a java program to check whether given candidate is eligible for voting or not. Handle user defined as well as system definedException.

 

Write a java program to check whether given candidate is eligible for voting or not. Handle user defined as well as system definedException.    

 

import java.util.InputMismatchException;

import java.util.Scanner;

 

class AgeBelow18Exception extends Exception {

    public AgeBelow18Exception(String message) {

        super(message);

    }

}

 

public class VotingEligibility {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

 

        try {

            System.out.print("Enter the candidate's age: ");

            int age = scanner.nextInt();

 

            if (age < 18) {

                throw new AgeBelow18Exception("Candidate is not eligible for voting as age is below 18.");

            } else {

                System.out.println("Candidate is eligible for voting.");

            }

        } catch (AgeBelow18Exception e) {

            System.err.println(e.getMessage());

        } catch (InputMismatchException e) {

            System.err.println("Invalid input. Please enter a valid age as a numeric value.");

        }

    }

}