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.

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) {


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("Rest of the code");


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