In this tutorial, we will learn about Custom Exception in Java. Custom Exceptions are also known as a user-defined exception. The main motive of creating a custom exception is to create a new exception according to project requirement. When you create a custom exception you have to inherit Exception class as a parent in your custom exception class. please check out the following example.

Example Program:

//creating an custom Exception class
class MyCustomException extends Exception{
  public MyCustomException(){
    System.out.println("Constucor of MyCustomException invoked");
  }
  public String getMessage() {
        return "Hello, This is getMessage() in MyCustomException";
  }
}

public class Example{
  public static void main(String args[]){
    try{
      System.out.println("In try block");
      throw new MyCustomException(); //throwing exception explicitly
    }catch(MyCustomException e){
      System.out.println(e.getMessage());
      System.out.println("In catch block");
    }
  }
}

Output:

In try block
Constucor of MyCustomException invoked
Hello, This is getMessage() in MyCustomException
In catch block