• Home
  • Testing
  • SAP
  • Web
  • Must Learn!
  • Big Data
  • Live Projects
  • AI
  • Blog

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.

 

 

Create 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 -
 

Create User Defined Exception in Java

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

 

YOU MIGHT LIKE: