Previous | Next | Trail Map | Writing Java Programs | Handling Errors using Exceptions


The throw Statement

All Java methods use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object. In the Java system, throwable objects are instances of any subclass of the Throwable class defined in java.lang .
throw someThrowableObject;
If you attempt to throw an object that is not throwable, the compiler will display an error message similar to the following
testing.java:10: Cannot throw class java.lang.Integer; it must be a subclass of class java.lang.Throwable.
	    throw new Integer(4);
	    ^
and refuse to compile your program. The next page, The Throwable Class and Its Subclasses, talks more about the Throwable class.

Let's look at the throw statement in context. The following method is taken from a class that implements a common stack object. The pop() method removes the top element from the stack and returns it. If the stack is empty this method throws an exception:

public Object pop() throws EmptyStackException {
    Object obj;

    if (size == 0)
        throw new EmptyStackException();

    obj = objectAt(size - 1);
    setObjectAt(size - 1, null);
    size--;
    return obj;
}
The pop() method checks to see if there are any elements on the stack. If the stack is empty (its size is equal to 0) then pop() instantiates a new EmptyStackException object and throws it. The EmptyStackException class is defined in the java.util package. Later pages in this lesson describe how you can create your own exception classes. For now, all you really need to remember is that you can only throw objects that inherit from the java.lang.Throwable class.

The throws Clause

You'll notice that the declaration of the pop() method contains this clause:
throws EmptyStackException
which declares that the method can throw an EmptyStackException. As you know, the Java language requires that methods either catch or declare all non-runtime exceptions that can be thrown within the scope of that method. You do this with the throws clause of the method declaration. For more information about this requirement see Java's Catch or Declare Requirement. Also, Declaring the Exceptions Thrown by a Method shows you in more detail how a method can declare the exceptions it can throw.


Previous | Next | Trail Map | Writing Java Programs | Handling Errors using Exceptions