Java Reference
In-Depth Information
12.4.1
Throwing an exception
Code 12.5 shows how an exception is thrown using a
throw statement
. Here, the
getDetails
method is throwing an exception to indicate that passing a
null
value for the key does not
make sense because it is not a valid key.
Code 12.5
Throwing an exception
/**
* Look up a name or phone number and return the
* corresponding contact details.
* @param key The name or number to be looked up.
* @return The details corresponding to the key,
* or null if there are none matching.
* @throws IllegalArgumentException if the key is invalid.
*/
public
ContactDetails getDetails(String key)
{
if
(key ==
null
){
throw new
IllegalArgumentException(
"null key in getDetails"
);
}
return
book.get(key);
}
There are two stages to throwing an exception. First, an exception object is created using the
new
keyword (in this case, an
IllegalArgumentException
object); then the exception
object is thrown using the
throw
keyword. These two stages are almost invariably combined in
a single statement:
Concept:
An
exception
is
an object repre-
senting details of
a program failure.
An exception is
thrown to indicate
that a failure has
occurred.
throw new
ExceptionType
("
optional-diagnostic-string
");
When an exception object is created, a diagnostic string may be passed to its constructor.
This string is later available to the receiver of the exception via the exception object's
get-
Message
and
toString
methods. The string is also shown to the user if the exception is not
handled and leads to the termination of the program. The exception type we have used here,
IllegalArgumentException
, is defined in the
java.lang
package and is regularly used to
indicate that an inappropriate actual parameter value has been passed to a method or constructor.
Code 12.5 also illustrates that the
javadoc
documentation for a method can be expanded to
include details of any exceptions it throws, using the
@throws
tag.
12.4.2
Checked and unchecked exceptions
An exception object is always an instance of a class from a special inheritance hierarchy. We
can create new exception types by creating subclasses in this hierarchy (Figure 12.1). Strictly
Search WWH ::
Custom Search