Pages

Wednesday, 23 April 2014

Example progams to throw our own exception.


In this particular blog we will see how to throw our own exception.

Source code:

public class MyOwnException {
    public static void main(String[] a){
        try{
            MyOwnException.Test(null);
        } catch(EmployeeException e){
            System.out.println("Inside catch block: "+e.toString());
        }
    }
    
    static void Test(String str) throws EmployeeException {
        if(str == null){
            throw new EmployeeException ("String val is null");
        }
    }
}
 class EmployeeException extends Exception {
     private String message = null;
      public EmployeeException (String message) {
        super(message);
        this.message = message;
    }
  }

   (or)

public class TestEmployeeException {
   public static void main(String[] args)throws Exception {
          int salary=120000;
           if(salary<20000){
               throw new MyOwnException(salary);
           }
           else{
               System.out.println("No exception");
           }
    }

}


public class MyOwnException extends Exception {

     private int salary;
     public MyOwnException(int salary){
         this.salary= salary;
     }
     public String toString(){
         String exception = "Salary Should be more than 20,000 "+salary;
         return exception;
     }
}


Note: The below two files should be different classes.

 
Thanks for reading !

No comments:

Post a Comment