Java Activity
Reg. no-23BCE10969
Name-Aadiy Khan
Q1-
In a voting eligibility system, a person must be at least 18 years old to vote. If a person's age is
below 18, the system should display an appropriate message indicating that they are not eligible
to vote.
Design a Java program that uses a user-defined exception to handle this situation. Create a
custom exception class named InvalidAgeException that extends the Exception class. Inside
this class, include a constructor that passes a message to the superclass (Exception)
constructor.
the In the main program, define a class VoteEligibility with a method validate(int age) that
throws InvalidAgeException if the age is less than 18. Use a try-catch block in the main()
method to handle the exception and display the custom error message.
Answer-
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
public class Main {
public static void validate(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age " + age + " is below the legal
voting limit of 18.");
} else {
[Link]("Welcome! You are eligible to vote.");
}
}
public static void main(String[] args) {
int[] testAges = {20, 16};
for (int age : testAges) {
try {
[Link]("Checking eligibility for age: " + age);
validate(age);
} catch (InvalidAgeException e) {
[Link]("Caught Exception: " + [Link]());
}
[Link]("-----------------------------------");
}
}
}
Output-