Thursday 27 February 2014

How to create user defined exceptions

You can create user defined exception by simply extending the Exception class.

Example
class MyException extends Exception{
 MyException(String msg){
  super(msg);
 }
}
    
class MyExceptionTest{
 static void print(int val)throws Exception{
  if(val < 0 ){
   throw new MyException("Values is less than zero:" + val);
  }
  else{
   System.out.println(val);
  }
 }

 public static void main(String args[]){
  try{
   print(-10);
  }
  catch(Exception e){
   System.out.println(e);
  }
 }
}
   
Output
MyException: Values is less than zero:-10
  
In the same way we can create RuntimeExceptions by extending the RuntimeException class.


Chained Exceptions                                                 checked vs unchecked exceptions                                                 Home

No comments:

Post a Comment