Custom Exceptions

Custom exception provides the facility to write our own methods or exception mechanism which are not part of Java predefined exception classes. Here we can store application related errors that can be used to show the exception to the end user.

Example
If user want to dispatch amount more than actual balance then user should get message like Insufficient fund and user can continue use the application further.

Lets see an example:

First we need to create an exception class for ex. InsufficientFundException and extends this class with Exception class.

public class InsufficientFundException extends Exception {

  public InsufficientFundException(String errorMsg) {
    super(errorMsg);
  }
}

 

Now we will use this exception in our class:

class ExceptionTest {

  public static void main(String[] args) throws InsufficientFundException {
    try {
      // Inserting code to get amount and in any situation inserting
      // amount greater than actual amount
      throw new InsufficientFundException("You have insufficient fund. Please try again!");
    } catch (InsufficientFundException e) {
      System.out.println(e.getMessage());
    }
    System.out.println("Rest of the code");
  }
}

Output:

You have insufficient fund. Please try again!
Rest of the code