Techoceanhub logo

How to make Custom Exceptions in Java

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.

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 .