Custom Checked and Custom Unchecked exception in Java.

Posted by manasvisawant45 on October 2, 2020 2:02 am


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

  1.  The class extends with java.lang.Exception.
  2. Custom checked exceptions are sometimes declared with method declaration with the help of the throws keyword.

Custom Unchecked Exception

  1. The class creating custom unchecked exceptions is extended with java. lang.RuntimeException.
  2. Custom unchecked exceptions are declared inside the method using the throw keyword.

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.