Java Reference
In-Depth Information
Code 12.15
continued
An exception class with
extra diagnostic
information
public class NoMatchingDetailsException extends Exception
{
// The key with no match.
private String key;
/**
* Store the details in error.
* @param key The key with no match.
*/
public NoMatchingDetailsException(String key)
{
this .key = key;
}
/**
* @return The key in error.
*/
public String getKey()
{
return key;
}
/**
* @return A diagnostic string containing the key in error.
*/
public String toString()
{
return "No details matching '" + key + "' were found." ;
}
}
The principle of including information that could support error recovery should particularly be kept
in mind when defining new checked exception classes. Defining formal parameters in an excep-
tion's constructor will help to ensure that diagnostic information is available. In addition, where
recovery is either not possible or not attempted, ensuring that the exception's toString method is
overridden to include appropriate information will help in diagnosing the reason for the error.
Exercise 12.33 In the address-book-v3t project, define a new checked exception class:
DuplicateKeyException . This should be thrown by the addDetails method if either of
the non-blank key fields of its actual parameter is already currently in use. The exception class
should store details of the offending key(s). Make any further changes to the user interface
class that are necessary to catch and report the exception.
Exercise 12.34 Do you feel that DuplicateKeyException should be a checked or
unchecked exception? Give reasons for your answer.
 
Search WWH ::




Custom Search