How to Create a Custom Exception in Java


We can create a custom exception class by extending the Exception class and implementing the constructors.

public class CustomException extends Exception {}

1. Creating a custom exception

We’ll want to ensure we implement every constructor listed in the Constructor Summary of the Exception documentation.

public class CustomException extends Exception {
  public CustomException() {}
  public CustomException(String message) {
    super(message);
  }
  public CustomException(Throwable cause) {
    super(cause);
  }
  public CustomException(String message, Throwable cause) {
    super(message, cause);
  }
}

In particular, we’ll want the last two constructors (i.e. Throwable(Throwable), Throwable(String, Throwable)) to support chained exceptions, which is very useful Æ’or debugging.

2. Using the custom exception

We can throw our custom exception just as we would any other exception.

try {
  if (/* Reason for exception */) {
    throw new CustomException();
  }
} catch(CustomException ex) {
  // Process exception
}