devxlogo

Create Your Own Exception

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 parameterspublic PrivateException() {}//constructor for exception descriptionpublic 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 !!!

");      //specify when  to generate the exception      if(a==b)        {        String description="In method "method1" a PrivateException         has been generated
 "+         " The "+a+" and "+b+" arguments are equal!!!
"+         " 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 !!!

");       //specify when to generate the exception       if((a*b)>10)          {         String description="In method "method2" a PrivateException          has been generated
 "+         " The "+a+" * "+b+" is grater that 10 !!!
"+         " 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();}  }}              

devx-admin

Share the Post: