Program that illustrates the Handling of user defined exceptions.
class MyAge extends Exception
{
public MyAge(String message)
{
super(message);
}
}
class Voter
{
String name;
int age;
public Voter(String name, int age)
{
this.name = name;
this.age = age;
}
public void verifyAge() throws MyAge
{
if (age < 18)
throw new MyAge("Sorry, " + name + ". You must be at least 18 years old to vote.");
else
System.out.println(name + ", your age is eligible for voting.");
}
}
class TestExc
{
public static void main(String[] args)
{
Voter voter1 = new Voter("Alice", 25);
Voter voter2 = new Voter("Bob", 15);
try
{
voter1.verifyAge();
voter2.verifyAge();
}
catch (MyAge e)
{
System.out.println("Exception: " + e.getMessage());
}
}
}
Output



0 Comments