Java Reference
In-Depth Information
should contain the name of the attribute. To represent the exception,
we create the NoSuchAttributeException class:
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 er-
ror. 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 excep-
tions are caught according to their type. For this reason, you would in-
vent 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. Pro-
grammers 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.
 
Search WWH ::




Custom Search