Answers for "create user defined exception in java"

1

java user defined exception example

class InvalidAgeException extends Exception{  
 InvalidAgeException(String s){  
  super(s);  
 }  
}  
class TestCustomException1{  
  
   static void validate(int age)throws InvalidAgeException{  
     if(age<18)  
      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...");  
  }  
} 

Output:Exception occured: InvalidAgeException:not valid
       rest of the code...
Posted by: Guest on April-21-2021
0

What are user defined exceptions

To create customized error messages we use userdefined exceptions. 
We can create user defined exceptions as checked or unchecked exceptions.
We can create user defined exceptions that extend Exception class or 
subclasses of checked exceptions so that userdefined exception becomes checked.
Userdefined exceptions can extend RuntimeException to create userdefined 
unchecked exceptions.

It is recommended to keep our customized exception class as unchecked,i.e 
we need to extend Runtime Exception class but not Excpetion class
Posted by: Guest on December-01-2020

Code answers related to "create user defined exception in java"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language