How to create custom exceptions in Java?

In Java, custom exceptions can be created by inheriting the Exception class or its subclasses. The following are the steps for creating custom exceptions.

  1. Create a class named with a custom exception’s name, usually ending with Exception, such as CustomException.
  2. Extend the Exception class or one of its subclasses to create a custom exception class. For example:
public class CustomException extends Exception {
  //...
}
  1. Customize exception class by adding constructors, you can add different constructors as needed. For example:
public class CustomException extends Exception {
  public CustomException() {
    super();
  }

  public CustomException(String message) {
    super(message);
  }

  public CustomException(String message, Throwable cause) {
    super(message, cause);
  }
}
  1. Additional methods or properties can be added to the custom exception class as needed.

When using custom exceptions, you can use the throw keyword to throw an instance of the custom exception at the specific point where it needs to be thrown. For example:

public void doSomething() throws CustomException {
  //...
  throw new CustomException("Something went wrong.");
}

Then, in the place where the doSomething method is called, a try-catch block can be used to catch and handle custom exceptions. For example:

try {
  doSomething();
} catch (CustomException e) {
  System.out.println("CustomException caught: " + e.getMessage());
}
bannerAds