Monday, 22 August 2016

Java Program to Create Custom Exception ?

For Creating Custom Exception we have to extends the Exception Class. And we can throw that exception if conditions not matches.
Here we are Creating InvalidAgeException , if age is less than 18 it will throw InvalidAgeException exception otherwise it will print valid age.

package exceptions.programs;
class InvalidAgeException extends Exception {

}
public class CustomExceptionExample {

public static void validateAge(int age){
try {
if(age < 18){
throw new InvalidAgeException();
}
else{
System.out.println("Valid Age");
}
} catch (InvalidAgeException e) {
e.printStackTrace();
}
}
public static void main(String[] args)  {
CustomExceptionExample.validateAge(5);
}
}
Program Output :-
exceptions.programs.InvalidAgeException
at exceptions.programs.CustomExceptionExample.validateAge(CustomExceptionExample.java:11)

at exceptions.programs.CustomExceptionExample.main(CustomExceptionExample.java:21)



No comments:

Post a Comment