User defined Exception in Java

You can also create your own exception sub class simply by extending java Exception class. You can define a constructor for your Exception sub class (not compulsory) and you can override the toString() function to display your customized message on catch.

class InvalidAgeException extends Exception{
 InvalidAgeException(String s){
  super(s);
 }
 public String toString()
 {
  return "Candidate is less than 18 year is not allowed to vote.";
 }
}
class ValidateCandidate{

   static void validate(int age) throws InvalidAgeException{
     if(age < 18)
         throw new InvalidAgeException("invalid candidate");
     else
         System.out.println("welcome to vote");
   }
   
   public static void main(String args[]){
      try{
        validate(13);
      }catch(Exception ex){
         System.out.println("Exception occured: "+ex);
      }

      System.out.println("rest of the code...");
  }
}

output here:

User defined Exception in Java

Points to Remember

  1. Extend the Exception class to create your own exception class.
  2. You don’t have to implement anything inside it, no methods are required.
  3. You can have a Constructor if you want.
  4. You can override the toString() function, to display customized message.

<<Previous <<   || Index ||   >>Next >>
Previous
Next