In our previous post, we have learned about types of exceptions, throws and throw. Today we are going to make a custom-defined exception, in simple means we will create an exception according to our requirement.
Basically, there are two types of exceptions, one is built-in exceptions and the other is User-Defined Exceptions. But today we are going to create a User-Defined Exception with a help of throw keyword. User-Defined exceptions are made to fulfill a specific purposes which sometimes built-in exception does not fulfill.
First, let us understand how to make a user-defined exception:-
- Creating a custom exception class that will be extending an Exception class or its child classes(which is a base class for all exceptions.)
- You can create a constructor or simple print a statement inside user-defined exception class.
Let us see a program below which will clearly explain the concept .
class MyException {
void validAge() {
int age=18;
try {
if (age<18) {
throw new AgeNotDefined();
}
}catch(AgeNotDefined e) {
e.printStackTrace();
System.out.println("Age is less than 18");
}
}
}
public class AgeNotDefined extends Exception {
public static void main(String[] args) {
System.out.println("UserDefinedException");
}
}
In the above example, we thr0w an exception AgeNotDefined which is a user-defined exception and remember that for creating user-defined exceptions we have to use a throw keyword. These Exceptions can have any name but you have to define it according to your need.
Feel free to try this example and comment below.