The previous post was just the briefing about custom Exception but now in this post, I am detailing about the custom checked and custom Unchecked exception. First, let us see the basic differences between these two.
Custom Checked Exceptions
- The class extends with java.lang.Exception.
- Custom checked exceptions are sometimes declared with method declaration with the help of the throws keyword.
Custom Unchecked Exception
- The class creating custom unchecked exceptions are extended with java.lang.RuntimeException.
- Custom unchecked exceptions are declared inside method using throw keyword .
Now let us see a basic program to understand a difference between two of the type of custom exception.
//custom Unchecked Exception
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 RuntimeException {
public static void main(String[] args) {
System.out.println("Custom Unchecked Exception");
}
}
//Custom checked exception
class UserException {
void checkNumber() throws NumberlessthanZero {
int num=-3;
try {
if (num<0) {
throw new NumberlessthanZero();
}
}catch(NumberlessthanZero e) {
e.printStackTrace();
System.out.println("Number is less than zero");
}
}
}
public class NumberlessthanZero extends Exception {
public static void main(String[] args) {
System.out.println(" Custom Checked Exception"); }
}
}
Feel free to try above given examples and comment below for any questions.