Creating Exceptions Tutorial

This tutorial will show you how you can create your own custom exception classes. Throughout my previous tutorials, I have demonstrated many exception classes that are derived from RuntimeException. Any class that is derived from the RuntimeException class (and Error) is considered an unchecked exception. Any class that is derived from the Exception class is considered to be a checked exception. I will go into detail on the differences between the two exception types in a future tutorial.
When creating your own exception classes you are free to extend either Exception or RuntimeException, it is not a good idea to extend Error or Throwable. The majority of the time you should extend the Exception class.
This tutorial will build on my Box class and demonstrate how deal with that nagging issue of negative or zero value arguments.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md CreateExceptions
C:\Java>cd CreateExceptions
C:\Java\CreateExceptions>Notepad CreateExceptions.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class CreateExceptions {
    public static void main(String args[]) {
        
        BoxOldWay old1 = new BoxOldWay();
        if ( !(old1.setLength(4) && old1.setHeight(-6) && old1.setWidth(7)) )  {
            System.out.println("Invalid argument measurement!");
        }      
        System.out.println("The volume of old1 is: " + old1.getVolume());

        BoxOldWay old2 = new BoxOldWay(-5, 5, 8);
        System.out.println("The volume of old2 is: " + old2.getVolume());

        System.out.println("\n----Error handling----\n");
    
        BoxNewImproved new1 = null;
        try {	
            new1 = new BoxNewImproved( -5, 5, 8 );
        } catch (InvalidMeasurementException e) {
            System.out.println(e.getMessage());
            new1 = new BoxNewImproved(); 
        }
	
        try {
            System.out.println("The volume of new1 is: " + new1.getVolume());
        } catch (InitializationIncompleteException e) {
            System.out.println(e.getMessage());
        }

        System.out.println("\nEnd of program");
    }
}

class BoxOldWay { // no error handling - rely on method return values for success/failure
    private int length = 0;
    private int height = 0;
    private int width = 0;

    BoxOldWay () { 
        super(); 
    }
    BoxOldWay (int length, int height, int width) { // what do we do about the constructor???
        this.length = length;
        this.height = height;
        this.width = width;
    }

    boolean setLength(int length) { // we can't be sure that the developer will check the return value!
        if (length <= 0) {
            return false;
        }
        this.length = length;
        return true;
    }

    boolean setHeight(int height) {
        if (height <= 0) {
            return false;
        }
        this.height = height;
        return true;
    }

    boolean setWidth(int width) {
        if (width <= 0) {
        return false;
    }
        this.width = width;
        return true;
    }

    int getVolume() { // we can't ensure that 0 values aren't part of the equation
        return (length * height * width);
    }
}

class BoxNewImproved {
    private int length = 0;
    private int height = 0;
    private int width = 0;

    BoxNewImproved () { 
        super(); 
    }
    BoxNewImproved (int length, int height, int width) throws InvalidMeasurementException {
        if (length <= 0 || height <= 0 || width <= 0) {
            throw new InvalidMeasurementException();
        }
        this.length = length;
        this.height = height;
        this.width = width;
    }

    int getVolume() throws InitializationIncompleteException {
        if (length <= 0 || height <= 0 || width <= 0 ) {
            throw new InitializationIncompleteException();
        }
        return (length * height * width);
    }
}

class InvalidMeasurementException extends Exception {
    InvalidMeasurementException() {
        super("Measurement argument cannot be 0 or negative");
    }
}

class InitializationIncompleteException extends Exception {
    InitializationIncompleteException() {
        super("Initialization of object state was not completed");
    }
}


Now switch back to the command prompt (CMD) and type in javac CreateExceptions.java and press Enter.
Now type in java CreateExceptions and press Enter.


C:\Java\CreateExceptions>javac CreateExceptions.java
C:\Java\CreateExceptions>java CreateExceptions
The volume of old1 is: 0
The volume of old2 is: -200

----Error handling----

Measurement argment cannot be 0 or negative
Initialization of object state was not completed


Final thoughts

When creating your own exception classes, the majority of the time you should extend the Exception class. I introduced a lot of new concepts into this tutorial like throw and throws. I will be going into more detail on the purpose of those two keywords in future tutorials.


Tutorials