public class NoSuchAttributeException extends Exception {
public final String attrName;
public NoSuchAttributeException(String name) {
super("No attribute named \"" + name + "\" found");
attrName = name;
}
}
NoSuchAttributeException extends Exception to add a constructor that takes the name of the
attribute; it also adds a public final field to store the data. The constructor invokes the superclass's constructor
with a string description of what happened. This custom exception type helps when writing code that catches
the exception because it holds both a human-usable description of the error and the data that created the error.
Adding useful data is one reason to create a new exception type.
Another reason to create a new exception type is that the type of the exception is an important part of the
exception data, because exceptions are caught according to their type. For this reason, you would invent
NoSuchAttributeException even if you did not want to add data. In this way, a programmer who
cared only about such an exception could catch it exclusive of other exceptions that might be generated either
by the methods of the Attributed interface, or by other methods used on other objects in the same area of
code.
In general, new exception types should be created when programmers will want to handle one kind of error
differently from another kind. Programmers can then use the exception type to execute the correct code rather
than examine the contents of the exception to determine whether they really care about the exception or they
have caught an irrelevant exception by accident.
12.2. tHRow
You throw exceptions using the tHRow statement:
throw expression;
where expression must evaluate to a value or variable that is assignable to Throwableor in simple
terms, a reference to a Throwable object. For example, here is an addition to AttributedImpl from
Chapter 4 that implements replaceValue:
public void replaceValue(String name, Object newValue)
throws NoSuchAttributeException
{
Attr attr = find(name); // look up the attr
if (attr == null) // it isn't found
throw new NoSuchAttributeException(name);
attr.setValue(newValue);
}
The replaceValue method first looks up the current Attr object for the name. If there isn't one, it throws
a new object of type NoSuchAttributeException, providing the constructor with the attribute name.
Exceptions are objects, so they must be created before being thrown. If the attribute does exist, its value is
replaced with the new value. You can also generate an exception by invoking a method that itself throws an