devxlogo

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();}  }}              

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  Five Early Architecture Decisions That Quietly Get Expensive

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.