Monday, 6 October 2014

Custom/User-Defined Exception

If you are creating your own Exception that is known as custom exception or user-defined exception.

Here is an small example that tells If age is less than 18 it throws an exception as "not valid"  else it prints as "Welcome to vote"

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..."); 
  }
}


O/P:
Exception occured: InvalidAgeException: not valid
rest of the code...




NOTE :
In above example we can extends Throwable class instead of Exception.
But we need to be careful that in our main method we need to catch that Throwable.
Otherwise we get RunTime Exception.

we need to rewrite as below
catch(Throwable e){
}
Print Friendly Version of this pagePrint Get a PDF version of this webpagePDF

No comments:

Simplest way to display Server Time in JSP using js

THE BELOW CODE WORKS ONLY IN JSP : <html> <body > <table width="95%" border="1" cellpadding="1...