When a program encounters an exceptional condition, it throws the exception like IOException, IllegalArgumentException etc.

Sometimes no standard class adequately represents the exceptional condition. In this condition programmer can choose to create his own exception class.

To create our own Exception existing type of exception are inherited, preferably one that is close in meaning to your new exception.

This code shows the use of user defined exception. In this code ApplicationException is user defined Exception.

 public class ApplicationException extends Exception {

  private int intError;
  
  ApplicationException(int intErrNo){
    intError = intErrNo;
  }

  ApplicationException(String strMessage){
    super(strMessage);
   }

   public String toString(){
    return "ApplicationException["+intError+"]";
   }  
}

class ExceptionDemo{

  static void compute(int a) throws ApplicationException{

    System.out.println("called compute(" +a +" )");

    if(a>10){
      throw new ApplicationException(a);
    }

    System.out.println("NORMAL EXIT");
  }

  public static void main(String[] args) {

    try{
      compute(1);
      compute(20);

    }catch(ApplicationException e){
      System.out.println("caught " + e);
    }
  }
}

Output:

called comute(1 )
mohti
called comute(20 )
caught ApplicationException[20]