Java Reference
In-Depth Information
There won't always be a human user around to prompt for alternative input. It might be the
client object's responsibility to log the error so that it can be investigated.
12.8.2 Erroravoidance
It should be clear that arriving at a situation where an exception is thrown will be, at worst, fatal
to the execution of a program and, at best, messy to recover from in the client. It can be simpler
to try to avoid the error in the first place, but this often requires collaboration between server
and client.
Many of the cases where an AddressBook object is forced to throw an exception involve null
parameter values passed to its methods. These represent logical programming errors in the cli-
ent that could clearly be avoided by simple prior tests in the client. Null parameter values are
usually the result of making invalid assumptions in the client. For instance, consider the follow-
ing example:
String key = database.search(zipCode);
ContactDetails university = contacts.getDetails(key);
If the database search fails, then the key it returns may well be either blank or null . Passing
that result directly to the getDetails method will produce a runtime exception. However,
using a simple test of the search result, the exception can be avoided and the real problem of a
failed zip code search can be addressed instead:
String key = database.search(zipCode);
if(key != null && key.length() > 0) {
ContactDetails university = contacts.getDetails(key);
... ...
}
else {
Deal with the zipcode error . . .
}
In this case, the client could establish for itself that it would be inappropriate to call the serv-
er's method. This is not always possible, and sometimes the client must enlist the help of the
server.
Exercise 12.33 established the principle that the addDetails method should not accept a
new set of details if one of the key values is already in use for another set. In order to avoid
an inappropriate call, the client could make use of the address book's keyInUse method, as
follows:
// Add what should be a new set of details to the address book.
if(contacts.keyInUse(details.getName()) {
contacts.changeDetails(details.getName(), details);
}
else if(contacts.keyInUse(details.getPhone()) {
contacts.changeDetails(details.getPhone(), details);
}
else {
Add the details . . .
}
 
Search WWH ::




Custom Search