Java Reference
In-Depth Information
A catch block names the type of exception it is designed to deal with in a pair of parentheses
immediately following the
catch
word. As well as the exception type name, this also includes
a variable name (traditionally, simply
e
or
ex
) that can be used to refer to the exception object
that was thrown. Having a reference to this object can be useful in providing information that
will support recovery from, or reporting of, the problem—e.g., accessing any diagnostic mes-
sage placed in it by the throwing method. Once the catch block has been completed, control
does
not
return to the statement that caused the exception.
Exercise 12.28
The
address-book-v3t
project includes some throwing of unchecked
exceptions if parameter values are
null
. The project source code also includes the checked
exception class
NoMatchingDetailsException
, which is currently unused. Modify the
removeDetails
method of
AddressBook
so that it throws this exception if its key
parameter is not a key that is in use. Add an exception handler to the
remove
method of
AddressBookTextInterface
to catch and report occurrences of this exception.
Exercise 12.29
Make use of
NoMatchingDetailsException
in the
changeDetails
method of
AddressBook
. Enhance the user interface so that the details of an existing entry
may be changed. Catch and report exceptions in
AddressBookTextInterface
that arise
from use of a key that does not match any existing entry.
Exercise 12.30
Why is the following not a sensible way to use an exception handler? Will
this code compile and run?
Person p = null;
try {
// The lookup could fail.
p = database.lookup(details);
}
catch(Exception e) {
}
System.out.println("The details belong to: " + p);
Note that in all the examples of try statements you have seen, the exception is not thrown
directly
by the statements in the try block, which is in the client object. Rather, the exception
arises
indirectly
, passed back from a method in the server object, which is called from the state-
ments within the try block. This is the usual pattern, and it would almost certainly be a mistake
to enclose a throw statement directly within a try statement.
12.5.3
Throwing and catching multiple exceptions
Sometimes a method throws more than one type of exception in order to indicate different sorts
of problems. Where these are checked exceptions, they must all be listed in the throws clause of
the method, separated by commas. For instance:
public void process()
throws EOFException, FileNotFoundException
Search WWH ::
Custom Search