0% found this document useful (0 votes)
7 views1 page

Custom Age Validation Exception in Java

The document defines a custom exception class 'InvalidAgeException' that extends the Exception class to handle age validation. The 'TestCustomException1' class includes a method 'validate' that throws this exception if the age is less than 18. In the main method, it demonstrates the exception handling by validating an age of 13, catching the exception, and printing the relevant messages.

Uploaded by

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

Custom Age Validation Exception in Java

The document defines a custom exception class 'InvalidAgeException' that extends the Exception class to handle age validation. The 'TestCustomException1' class includes a method 'validate' that throws this exception if the age is less than 18. In the main method, it demonstrates the exception handling by validating an age of 13, catching the exception, and printing the relevant messages.

Uploaded by

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

// class representing custom exception

class InvalidAgeException extends Exception


{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}
// class that uses custom exception InvalidAgeException
public class TestCustomException1
{
// method to check the age
static void validate (int age) throws InvalidAgeException{
if(age < 18){

// throw an object of user defined exception


throw new InvalidAgeException("age is not valid to vote");
}
else {
[Link]("welcome to vote");
}
}

// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
[Link]("Caught the exception");

// printing the message from InvalidAgeException object


[Link]("Exception occured: " + ex);
}

[Link]("rest of the code...");


}
}

Output:

You might also like