7.1.4 How to Throw Your Own Exception

Let us have a look at the following applet. Note that the disk may leave the box, e.g. take x=200, y=100, size = 50. Suppose this is unwanted behaviour.

We would like to throw our own CircleSizeException if the circle does not fit into the box. In the next applet we include a test for this, which will do the throw-action.

For throwing the exception, we have to do two things:

  1. declare the class.
    class CircleSizeException extends Exception {
      
      CircleSizeException ( ) { }
    
      CircleSizeException (String str) {
            super(str);
      }
    }
    
  2. throw the exception at the right location
    void checkSize (int x, int y, int size) throws CircleSizeException {
      if (x + size > 200 || x < 0 || 
          y + size > 200 || y < 0) 
        throw new CircleSizeException("The disk will not fit in the box."); 
      } 
    }