Java Reference
In-Depth Information
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 excep-
tion. 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 sys-
tems for hospitals. One method might compute the patient's average daily tempera-
ture by accessing the patient's record in some file and dividing the sum of the
temperatures by the number of times the temperature was taken. Now suppose these
methods are used for creating different systems to be used in different situations.
What should happen if the patient's temperature was never taken and so the averag-
ing would involve a division by zero? In an intensive-care unit, this would indicate
something is very wrong. So for that system, when this potential division by zero
would occur, an emergency message should be sent out. However, for a system that
is to be used in a less urgent setting, such as outpatient care or even in some noncrit-
ical wards, it might have no significance, and so a simple note in the patient's record
would suffice. In this scenario, the method for doing the averaging of the tempera-
tures should throw an exception when this division by zero occurs, list the exception
in the throws clause, and let each system handle the exception case in the way that is
appropriate to that system.
Search WWH ::




Custom Search