Techoceanhub logo

Custom Checked and Custom Unchecked exception in Java.

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

  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 are extended with java.lang.RuntimeException.
  2. 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.

Share:

Categories

Archives

Related Posts

Array Destructuring

Array Destructuring Array destructuring is a powerful syntax introduced in ES6 that allows you to unpack elements from an array

Read More »

Explore our Affiliated partner links

hostgator website plan

Hostgator

Best Website hosting plans & Best for 24/7 support.

hostinger webhosting plan

Hostinger

Reasonable website hosting packages for small business & 24/7 Email support

Elementor pro

Design Worpdress website quickly using Elementor Builder and AI

buy elementor website templates

Buy Elementor Website Template

Buy ready made Elementor Website Template from us & Get Free Elementor pro licence for 1 year .