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.
Here's an example of a throw
statement:
throw someThrowableObject;
If you attempt to throw an object that is not throwable, the compiler
refuses to compile your program and displays 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);
^
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:
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 throw only objects that inherit
from the java.lang.Throwable
class.