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

More often than not, in your programming projects, you will be required to define java custom Exceptions also called User-defined Exceptions. 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.

Assignment: 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: