THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

12.3.1. tHRows Clauses and Method Overriding


When you override an inherited method, or implement an inherited abstract method, the tHRows clause of
the overriding method must be compatible with the throws clause of the inherited method (whether abstract
or not).


The simple rule is that an overriding or implementing method is not allowed to declare more checked
exceptions in the tHRows clause than the inherited method does. The reason for this rule is quite simple:
Code written to deal with the original method declaration won't be prepared to catch any additional checked
exceptions and so no such exceptions are allowed to be thrown. Subtypes of the declared exceptions can be
thrown because they will be caught in a catch block for their supertype. If the overriding or implementing
method does not throw a checked exception then it need not redeclare that exception. For example, as you saw
in "Strategies for Cloning" on page 101, a class that implements Cloneable need not declare that clone
may throw a CloneNotSupportedException. Whether to declare it or not is a matter of designif you
declare it in the overriding method then subclasses of your class will be allowed to throw the exception in that
method, otherwise they will not.


If a method declaration is multiply inheritedthat is, it exists in more than one inherited interface, or in both an
inherited interface and a superclassthen the tHRows clause of that method must satisfy all the inherited
tHRows clauses. As we discussed in "Inheriting, Overriding, and Overloading Methods" on page 125, the
real issue in such multiple inheritance situations, is whether a single implementation of a method can honor all
the inherited contracts.


12.3.2. throws Clauses and Native Methods


A native method declaration (see page 74) can provide a throws clause that forces all users of that method
to catch or redeclare the specified checked exceptions. However, the implementation of native methods is
beyond the control of the Java compiler and so they cannot be checked to ensure that only the declared
exceptions are thrown. Well-written native methods, however, will throw only those checked exceptions that
they declare.


Exercise 12.1: Create an ObjectNotFoundException class for the LinkedList class you built in
previous exercises. Add a find method that looks for an object in the list and either returns the
LinkedList object that contains the desired object or throws the exception if the object isn't found in the
list. Why is this preferable to returning null if the object isn't found? What additional data if any should
ObjectNotFoundException contain?


12.4. TRy, catch, and finally


You catch exceptions by enclosing code in TRy blocks. The basic syntax for a TRy block is:


try {
statements
} catch (exception_type1 identifier1) {
statements
} catch (exception_type2 identifier2) {
statements
...
} finally {
statements
}

Free download pdf