dcsimg
Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Language: Java
Expertise: Intermediate
Mar 11, 2008

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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();}
  }
}              
Leonard Anghel
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date