How can we create a custom exception in Java?



Sometimes it is required to develop meaningful exceptions based on the application requirements. We can create our own exceptions by extending Exception class in Java

User-defined exceptions in Java are also known as Custom Exceptions.

Steps to create a Custom Exception with an Example

  • CustomException class is the custom exception class this class is extending Exception class.
  • Create one local variable message to store the exception message locally in the class object.
  • We are passing a string argument to the constructor of the custom exception object. The constructor set the argument string to the private string message.
  • toString() method is used to print out the exception message.
  • We are simply throwing a CustomException using one try-catch block in the main method and observe how the string is passed while creating a custom exception. Inside the catch block, we are printing out the message.

Example

class CustomException extends Exception {
   String message;
   CustomException(String str) {
      message = str;
   }
   public String toString() {
      return ("Custom Exception Occurred : " + message);
   }
}
public class MainException {
   public static void main(String args[]) {
      try {
         throw new CustomException("This is a custom message");
      } catch(CustomException e) {
         System.out.println(e);
      }
   }
}

Output

Custom Exception Occurred : This is a custom message

Advertisements