Java Reference
In-Depth Information
where there may be a possibility of the client effecting a recovery. One problem with this
policy is that it assumes that the server is aware enough of the context in which it is being
used to be able to determine whether client recovery is likely or unlikely to be possible.
Another rule of thumb is to use unchecked exceptions for situations that could reasonably be
avoided. For instance, calling a method on a variable containing null is the result of a logical
programming error that is completely avoidable, and the fact that NullPointerException is
unchecked fits this model. It follows that checked exceptions should be used for failure situations
that are beyond the control of the programmer, such as a disk becoming full when trying to write
to a file or a network operation failing because a wireless network connection has dropped out.
The formal Java rules governing the use of exceptions are significantly different for unchecked
and checked exceptions, and we shall outline the differences in detail in Sections 12.4.4 and
12.5.1, respectively. In simplified terms, the rules ensure that a client object calling a method
that could throw a checked exception will contain code that anticipates the possibility of a prob-
lem arising and that attempts to handle the problem whenever it occurs. 3
Exercise 12.23 List three exception types from the java.io package.
Exercise 12.24 Is SecurityException from the java.lang package a checked or an
unchecked exception? What about NoSuchMethodException ? Justify your answers.
12.4.3
The effect of an exception
What happens when an exception is thrown? There are really two effects to consider: the effect
in the method where the problem is discovered and the exception is thrown, and the effect in the
caller of the problem method.
When an exception is thrown, the execution of the current method finishes immediately; it does not
continue to the end of the method body. A consequence of this is that a method with a non- void
return type is not required to execute a return statement on a route that throws an exception. This
is reasonable, because throwing an exception is an indication of the throwing method's inability to
continue normal execution, which includes not being able to return a valid result. We can illustrate
this principle with the following alternative version of the method body shown in Code 12.5:
if(key == null) {
throw new IllegalArgumentException("null key in getDetails");
}
else {
return book.get(key);
}
The absence of a return statement in the route that throws an exception is acceptable. Indeed,
the compiler will indicate an error if any statements are written following a throw statement,
because they could never be executed.
3
In fact, it is still all too easy for the writer of the client to adhere to the rules in principle but to fail to
attempt a proper recovery from the problem, which rather subverts their purpose!
 
Search WWH ::




Custom Search