Handling Errors using 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 the Throwable class defined in java.lang .If you attempt to throw an object that is not throwable, the compiler will display an error message similar to the followingthrow someThrowableObject;and refuse to compile your program. The next page, The Throwable Class and Its Subclasses, talks more about the Throwable class.testing.java:10: Cannot throw class java.lang.Integer; it must be a subclass of class java.lang.Throwable. throw new Integer(4); ^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. If the stack is empty this method throws an exception: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 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 thepop()
method contains this clause: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 thethrows EmptyStackExceptionthrows
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.
Handling Errors using Exceptions |