User Defined Exception

User-defined Exception:


  • User-Defined Exception or custom exception is creating your own exception class.
  • This can be done by extending the class Exception.


  • Notes:
    • 1. User-defined exceptions must extend Exception class.
    • 2. The exception is thrown using the throw keyword.


  • Example:

class JavaException{
   public static void main(String args[]){
  try{
       throw new MyException(2);
  }
 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) ;
  }
}
  • Example:
Example:
class InvalidAgeException extends Exception{  
 InvalidAgeException(String s){  
  super(s);  
 }  
}  

class TestCustomException1{  
  
   static void validate(int age)throws InvalidAgeException{  
     if(age<18 b="" nbsp="">
      throw new InvalidAgeException("not valid");  
     else  
      System.out.println("welcome to vote");  
   }  
   public static void main(String args[]){  
      try{  
      validate(13);  
      }catch(Exception m){System.out.println("Exception occured: "+m);}  
  
      System.out.println("rest of the code...");  
  }  
}  

Thanks a lot for query or your valuable suggestions related to the topic.

Previous Post Next Post

Contact Form