Java Reference
In-Depth Information
Code 12.6
Checking for an illegal
parameter value
public ContactDetails getDetails(String key)
if (key == null ) {
throw new IllegalArgumentException( "null key in getDetails" );
if (key.trim().length() == 0) {
throw new IllegalArgumentException(
"Empty key passed to getDetails" );
return book.get(key);
It is well worth having a method conduct a series of validity checks on its parameters before
proceeding with the main purpose of the method. This makes it less likely that a method will get
part way through its actions before having to throw an exception because of bad parameter val-
ues. A particular reason for avoiding this situation is that partial mutation of an object is likely
to leave it in an inconsistent state for future use. If a method fails for any reason, the object on
which it was called should ideally be left in the state it was before the operation was attempted.
Exercise 12.25 Review all of the methods of the AddressBook class and decide whether
there are any additional situations in which they should throw an IllegalArgumentException .
Add the necessary checks and throw statements.
Exercise 12.26 If you have not already done so, add javadoc documentation to describe
any exceptions thrown by methods in the AddressBook class.
Exercise 12.27 UnsupportedOperationException is an unchecked exception defined
in the java.lang package. How might this be used in an implementation of the java.util.
Iterator interface to prevent removal of items from a collection that is being iterated over?
Try this out in the LogfileReader class of the weblog-analyzer project from Chapter 4.
Preventing object creation
An important use for exceptions is to prevent objects from being created if they cannot be placed
in a valid initial state. This will usually be the result of inappropriate parameter values being
passed to a constructor. We can illustrate this with the ContactDetails class. The constructor
is currently fairly forgiving of the parameter values it receives: it does not reject null values but
replaces them with empty strings. However, the address book needs at least a name or phone num-
ber from each entry to use as a unique index value, so an entry with both name and phone fields
blank would be impossible to index. We can reflect this requirement by preventing construction of
a ContactDetails object with no valid key details. The process of throwing an exception from
a constructor is exactly the same as throwing one from a method. Code 12.7 shows the revised
constructor that will prevent an entry from ever having both name and phone fields blank.
Search WWH ::

Custom Search