Handling Errors with Exceptions |
All Java methods use thethrow
statement to throw an exception. Thethrow
statement requires a single argument: a throwable object. In the Java system, throwable objects are instances of any subclass of theThrowable
class. Here's an example of athrow
statement: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:throw someThrowableObject;The next page, Thetesting.java:10: Cannot throw class java.lang.Integer; it must be a subclass of class java.lang.Throwable. throw new Integer(4); ^Throwable
Class and Its Subclasses, talks more about theThrowable
class.Let's look at the
throw
statement in context. The following method is taken from a class that implements a common stack object. Thepop
method removes the top element from the stack and returns it:Thepublic Object pop() throws EmptyStackException { Object obj; if (size == 0) throw new EmptyStackException(); obj = objectAt(size - 1); setObjectAt(size - 1, null); size--; return obj; }pop
method checks to see if there are any elements on the stack. If the stack is empty (its size is equal to 0), thenpop
instantiates a newEmptyStackException
object and throws it. TheEmptyStackException
class is defined in thejava.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 thejava.lang.Throwable
class.The
throws
ClauseYou'll notice that the declaration of thepop
method contains this clause:Thethrows EmptyStackExceptionthrows
clause specifies that the method can throw anEmptyStackException
. 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 thethrows
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.
Handling Errors with Exceptions |