How to Create User Defined Exception in Java

What is User Defined Exception in Java?

User Defined Exception or custom exception is creating your own exception class and throws that exception using ‘throw’ keyword. This can be done by extending the class Exception.


 User Defined Exception in Java

There is no need to override any of the above methods available in the Exception class, in your derived class. But practically, you will require some amount of customizing as per your programming needs.

Example: To created a User-Defined Exception Class

Step 1) Copy the following code into the editor

class JavaException{
   public static void main(String args[]){
  try{
       throw new MyException(2);
       // throw is used to create a new exception and throw it.
  }
 catch(MyException e){
    System.out.println(e) ;
 }
}
}
class MyException extends Exception{
   int a;
   MyException(int b) {
     a=b;
   }
   public String toString(){
     return ("Exception Number =  "+a) ;
  }
}

Step 2) Save , Compile & Run the code. Excepted output –


 User Defined Exception in Java

NOTE: The keyword throw is used to create a new Exception and throw it to the catch block.