Exceptions: Throw Statement Tutorial

The throw keyword is used to manually cause an exception to occur. A throw statement can throw either a checked or unchecked exception.
The structure of a throw statement looks like this:
( throw ) ( new ) ( ExceptionClass(argument list) )( ; )

In this tutorial I will demonstrate how to throw an unchecked exception. Throwing a checked exception requires an understanding how to use the throws keyword, so I will demonstrate how to throw a checked exception in my next tutorial.

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>md ExceptionThrow
C:\Java>cd ExceptionThrow
C:\Java\ExceptionThrow>Notepad ExceptionThrow.java

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

class ExceptionThrow {
    public static void main(String args[]) {
        Box box1 = new Box(10, 3, 4);
        System.out.println("The volume of box1 is: " + box1.calculateVolume());

        Box box2 = new Box(-6, 8, 7);
        System.out.println("The volume of box2 is: " + box2.calculateVolume());

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

    Box(int length, int height, int width) {
        if(length <= 0 || height <= 0 || width <= 0 ) {
            throw new IllegalArgumentException(); // subclass of RuntimeException - unchecked exception
        this.length = length;
        this.height = height;
        this.width = width;
    int calculateVolume() {
        return ( length * height * width );

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

C:\Java\ExceptionThrow>javac ExceptionThrow.java
C:\Java\ExceptionThrow>java ExceptionThrow
The volume of box1 is: 120
Exception in thread "main" java.lang.IllegalArgumentException
    at Box.(ExceptionThrow.java:18)
    at ExceptionThrow.main(ExceptionThrow.java:6)

Final thoughts

Stay tuned for my next tutorial where I will show you how to throw a checked exception.