Trail: Essential Java Classes
|
Lesson: Handling Errors with 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.
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.
The throws Clause
You'll notice that the declaration of the pop method contains this
clause:
throws EmptyStackException
The throws clause specifies that the method can throw an EmptyStackException.
As you know, the Java language requires that methods either catch or
specify all checked 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 Specify Requirement.
Also, Specifying the Exceptions Thrown by a Method
shows you in more detail how a method can specify the exceptions it can throw.
|