11.7 Creating Your Own Exception Classes

The Java platform provides a lot of exception classes you can use, however, it does not provide all the exception classes you will ever need. You can create your own exception classes by extending the Exception class or one of its subclasses.

Following class extends the Exception class. Exception class typically have two constructors: The first takes no arguments, and the second takes a single string as an argument.

public class NegativeValueException extends Exception
{
    public NegativeValueException()
    {
        super();
    }
    public NegativeValueException(double value)
    {
        super("Negative Value: " + value);
    }
}        

Recall the Rectangle class from section 6.3. This class holds the data for a rectangle. There are a number of errors that could cause a Rectangle object. Here are some specific examples:

• A negative value of length or width is passed to the constructor.
• A negative number of length or width is passed to the set method.

We have created our own exceptions NegativeValueException. Now we can rewrite the Rectangle class so it throws one of our custom exceptions when any of these errors occur:


public class Rectangle
{
   private double length;
   private double width;

   public Rectangle()
   {
      length = 0.0;
      width  = 0.0;
   }

   public Rectangle(double l, double w) throws NegativeValueException
   {
      if(l < 0)
      {
         throw new NegativeValueException(l);
      }
      if(w < 0)
      {
         throw new NegativeValueException(w);
      }
      length = l;
      width  = w;
   }

   public void set(double l, double w) throws NegativeValueException
   {
      if(l < 0)
      {
         throw new NegativeValueException(l);
      }
      if(w < 0)
      {
         throw new NegativeValueException(w);
      }
      length = l;
      width  = w;
   }

   public double getArea()
   {
      return length * width;
   }

   public double getPerimeter()
   {
      return 2 * (length + width);
   }
}

Note that NegativeValueException extends the Exception class. This means that it is a checked exception class. Because of this, the constructor and setter header must have a throws clause.

Following program demonstrates how constructor of Rectangle class throws exception and handles it.

public class RectangleDemo
{
   public static void main(String[] args)
   {
      try
      {
         // Create a Rectangle object with negative values
         Rectangle rectangle = new Rectangle(-3.5, 4.2);

         System.out.println("Area of Rectangle is "
                         + rectangle.getArea());
      }
      catch(NegativeValueException ex)
      {
          ex.printStackTrace();
      }
   }
}

Sample Run

NegativeValueException: Negative Value: -3.5
at Rectangle.<init>(Rectangle.java:16)
at RectangleDemo.main(RectangleDemo.java:8)