Course Content‎ > ‎Session 10‎ > ‎

Custom Exception Classes

Creating your own Exception classes

You can either use the Exception classes provided by the Java Development environment or you can create your own exception classes. If you decide to write your own exception classes, it will be necessary for them to be a subclass of Throwable/Exception. This allows custom exceptions to be generated using throw and caught in the same way as normal exceptions. The following example creates an exception illegalValue, this is tested for in the method print, if one of the values is found to be illegal the exception is thrown, it is caught by the main method.

class illVal extends Exception
{
      int error;
      String desc;
      illVal() { }
      illVal(int error, String desc) {
    this.error = error;
    this.desc = desc;
      }
      void fix()
      {
    switch(error)
    {
        case 1:fixone();break;
    }
      }
      void fixone() {
        System.out.println("demo print for fixing one");
      }
}

class userExc
    {
        int value1, value2;
        userExc (int a, int b)
        {
            value1 = a;
            value2 = b;
        } 
       
        // causes it, but does not catch it
        void print () throws illVal
        {
            if  ((value1 < 0) || (value2 > 0))
                throw new illVal (1, "Oh no!");
           
            /* if test is true then the exception is thrown and no other
               statements in this method are executed, the next method in
               the call-stack is examined for the relevant catch. */
               
            System.out.println ("Value 1 = " + value1);
            System.out.println ("Value 2 = " + value2);
        }
    }

class runCX
{
        public static void main (String args[]) throws Exception
        {
            userExc vals = new userExc (-1, 20);
           
            // values will generate an exception in print
            try
            {
                vals.print();
            }
            catch (illVal e) // the custom exception
            {
                System.out.println ("Illegal Values: caught in main");
        e.fix();
            }
        }
}
   

ć
Sukhjit Singh,
Mar 5, 2012, 8:10 PM
Comments