Java Reference
In-Depth Information
object of the derived class might be used anyplace an object of the base class can be used,
so an overridden method must fit into any code written for an object of the base class.
When to Use Exceptions
So far, most of our examples of exception handling have been unrealistically simple.
A better guideline for how you should use exceptions is to separate throwing an
exception and catching the exception into separate methods. In most cases, you should
include any throw statement within a method definition, list the exception class in
a throws clause for that method, and place the try and catch blocks in a different
method . In outline form, the technique is as follows:
public void yourMethod() throws YourException
{
...
throw new YourException( <Maybe an argument.> );
...
}
Then, when yourMethod is used by some otherMethod , the otherMethod must
account for the exception. For example,
public void otherMethod()
{
...
try
{
...
yourMethod();
...
}
catch (YourException e)
{
<Handle exception.>
}
...
}
Even this kind of use of a throw statement should be reserved for cases where
it is unavoidable. If you can easily handle a problem in some other way, do not throw
an exception. Reserve throw statements for situations in which the way the exceptional
condition is handled depends on how and where the method is used . If the way that the
exceptional condition is handled depends on how and where the method is invoked,
then the best thing to do is to let the programmer who invokes the method handle the
exception. In all other situations, it is preferable to avoid throwing exceptions. Let's
outline a sample scenario of this kind of situation.
Suppose you are writing a library of methods to deal with patient monitoring systems
for hospitals. One method might compute the patient's average daily temperature by
 
Search WWH ::




Custom Search