0% found this document useful (0 votes)
2 views2 pages

Java Activity

The document describes a Java program that checks voting eligibility based on age, requiring a minimum age of 18. It includes a custom exception class, InvalidAgeException, to handle cases where the age is below the legal limit. The main program tests this functionality with an array of ages and displays appropriate messages based on eligibility.

Uploaded by

Aadiy Khan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Java Activity

The document describes a Java program that checks voting eligibility based on age, requiring a minimum age of 18. It includes a custom exception class, InvalidAgeException, to handle cases where the age is below the legal limit. The main program tests this functionality with an array of ages and displays appropriate messages based on eligibility.

Uploaded by

Aadiy Khan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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-

You might also like