The previous post was just the briefing about custom Exception but now in this post, I am detailing the custom checked and custom Unchecked exception. First, let us see the basic differences between these two.
Custom Checked Exceptions
Custom Unchecked Exception
Now let us see a basic program to understand the 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.
Copyright ©TechOceanhub All Rights Reserved.