Java

How to Create a User-Defined Exception in Java

A run-time error that happens while a process is executed is an exception. The program abruptly ends when an exception occurs, and the code after the line that caused the exception will not execute. In Java, exception classes such as ArithmeticException, and NullPointerException are already defined in the “Exception” class. However, you can make a user-defined exception in Java and use the throw keyword with them.

This manual will teach the method of creating Java user-defined exceptions.

How to Create a User-Defined Exception in Java?

In Java, you can create an exception and throw it utilizing the “throw” keyword. User-defined or custom exceptions are the names given to these exceptions.

To create a user-defined exception, first, you will extend the class with the “Exception” class and then use one of the below-mentioned methods:

Let’s understand both methods for creating user-defined exceptions with examples.

Method 1: Create a User-Defined Exception in Java Using getMessage() Method

In this section, we will use a “getMessage()” method to throw an exception with the “throw” keyword. We will pass a String that is used as an exception to the constructor of the parent “Exception” class by invoking the “super()” method in the present class constructor.

Syntax

Follow the given syntax for user-defined exception:

obj.getMessage();

Example 1

First, we will extend our class to the “Exception” class, then create a parameterized constructor that takes a String which will be thrown as an exception. In the constructor of the “Example” class, we will pass the String type parameter “s” and call the “super()” method with argument “s” that is passed to a constructor of the parent class:

publicExample(String s)
        {
    super(s);
           }

In the main() method, first we will create an object of the class and pass a string as an argument because the class contains a parameterized constructor. Then, throw an exception with the object of the class. These operations will be added in a try-catch block. Next, in the catch block, we will call the getMessage() method to print the message passed to the parent Exception class using the super() method:

publicstaticvoidmain(String[] args) {
    try {
         Example ex= new Example("Invalid Entry");
    throw ex;
    } catch (Example e) {
         System.out.println("Caught exception");
         System.out.println(e.getMessage());
    }
}

The user-defined exception is thrown:

It is not mandatory that you pass a String to a parent class using the super() method, you can also create a user-defined exception by calling a parent’s constructor without passing any parameter.

Example 2

In this example, we will create a user-defined exception without printing any message. Here, first, we will create a “UserDefinedException” class that extends to the “Exception” class:

class UserDefinedException extends Exception{ }

In the main() method of the “Example” class, we will throw an exception by creating a new object of the user-defined exception class. In the catch block, we will call the getMessage() method to print the message; however, it will print none because we will not pass any message to it:

publicclassExample{
    publicstaticvoidmain(String[] args) {
        try {
            thrownew UserDefinedException();
        }catch (UserDefinedException ue) {
             System.out.println("Caught exception");
             System.out.println(ue.getMessage());
        }
       }
}

Output

Let’s see how we can print exception details rather than specifying it in the parent class constructor.

Method 2: Create a User-Defined Exception Using toString() Method

If you want to print some details related to the exception, use the “toString()” method.

Syntax

Use the given syntax for printing message in user-defined exception:

public String toString(){
    return ("Message") ;
      }

Example

Here, we will create a toString() method in the user-defined exception class called “UserDefinedException“ by extending it with an “Exception” class. The method will return the string that will be printed out:

classUserDefinedExceptionextendsException{
    public String toString(){
    return ("The Exception is occured") ;
      }
}

In the main() method, we will call throw the exception using the “throw” keyword by creating a new object of the user-defined class in a try block:

publicclassExample{
    publicstaticvoidmain(String[] args) {
        try {
            thrownew UserDefinedException();
        }catch (UserDefinedException ue) {
             System.out.println("Caught exception");
             System.out.println(ue);
        }
    }
}

Output

We have compiled all the ways to create a user-defined exception in Java.

Conclusion

For creating a user-defined exception in Java, you will first extend the class to the Exception class, then use two methods, getMessage() and toString() methods. These methods are used to print the messages as an exception. The getMessage() method prints the message passed to the parent class constructor, while the toString() method returns the string that will be used as an exception message. In this manual, we explained the methods for creating a Java user-defined exception with examples.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.