Saturday, April 28, 2012

Create Your Own Exception

Here's an example of how to create an exception. You can extend this example as needed for your own applications. The important principle is the exeption's mechanism, not its subject: 

class PrivateException extends Exception{

//constructor without parameters
public PrivateException() {}

//constructor for exception description
public PrivateException(String description)
    {
    super(description);
    }
}

class Test
     {
     public Test(){}
     
     //this method will throw a PrivateException
     void method1(int a ,int b) throws PrivateException
      {
      System.out.println("You called method1 !!!\n\n");
      //specify when  to generate the exception
      if(a==b)
        {
        String description="In method \"method1\" a PrivateException 
        has been generated\n "+ 
        " The "+a+" and "+b+" arguments are equal!!!\n"+ 
        " Call this method with no equal arguments.";
        throw new PrivateException(description);
        }
      }
             
     //this method will throw a PrivateException
      void method2(int a, int b)throws PrivateException
       {
       System.out.println("You called method2 !!!\n\n");
       //specify when to generate the exception
       if((a*b)>10) 
         {
         String description="In method \"method2\" a PrivateException 
         has been generated\n "+
         " The "+a+" * "+b+" is grater that 10 !!!\n"+
         " Call this method with smaller arguments.";
         throw new PrivateException(description);
         }
       }       
     }

public class TestPrivateException{
 public static void main(String[] args)
  {
  Test t=new Test();
  try{
     t.method1(22,20); //NO EXCEPTION 
     t.method2(11,23); //EXCEPTION   
     }catch(PrivateException e)
       {e.printStackTrace();}
  }
}              

No comments:

Post a Comment