Saturday, July 28, 2012

How to create Your Own Exception in Java ?


1)Create a class called (ExceptionCaught) extending Exception Superclass
2)Override its Constructor with a String or an int variable
3)Override the Object classes toString method with the instance String or int variable of the class and use it by returning back the value.It Will be useful when System.out.println(e) is called.
4)Whereever you feel like Checked Exception might occur in Your Main Class (Use throws ExceptionCaught for methods since you already know it is a Checked Exception) just use throw to throw your Own Custom defined Exception and that throw new ExceptionCaught will call our Custom Defined Exception Constructor and Steps 2-3 follows.
5)Now in catch block, when you write System.out.println(e), it automatically goes to
System.out.println(e.toString()) and thus getting the result (which is already stored in the Step3).
(A)
package pack2;                                                                              
public class ExceptionCaught  extends Exception{                                                                                
            private String InJail;                                                     
            ExceptionCaught (String CaughtIn){                                         
                        InJail = CaughtIn;                                                     
            }                                                                           
            public String toString(){                                                  
                        return "Inside ExceptionJail is [[["+InJail+"]]]";                     
            }                                                                           
}                                                                              
                                                                               
(B)
package pack2;
public class ExceptionDemo{
      private static String name;
      static void UsualMethod(String a) throws ExceptionCaught{
            if(a.equals("3"))
                  throw new ExceptionCaught(a);
      }
      public static void main(String args[]){
            try
            {
              for(int suspectedthiefs=1;suspectedthiefs<=5;suspectedthiefs++)
              {
                    name = ""+suspectedthiefs;
                    UsualMethod(name);
                    System.out.println(" "+suspectedthiefs+", not a thief");
              }
            }
            catch (Exception e) {
                  System.out.println(e + " and he remaining have been detained for further Questioning");
            }          
      }
}

The Result is
----------------
1 not a thief
2 not a thief
Inside ExceptionJail is [[[3]]]and remaining have been detained for Questioning

No comments:

Post a Comment