Java Reference
In-Depth Information
Notifying the user
The most obvious way in which an object might respond when it detects something wrong is
to try to notify the application's user in some way. The main options are either to print an error
message using System.out or System.err or to display an error message alert window.
The two main problems with both approaches are:
They assume that the application is being used by a human user who will see the error mes-
sage. There are many applications that run completely independently of a human user. An
error message, or an error window, will go completely unnoticed. Indeed, the computer run-
ning the application might not have any visual-display device connected to it at all.
Even where there is a human user to see the error message, it will be rare for that user to be in
a position to do something about the problem. Imagine a user at an automatic teller machine
being confronted with a NullPointerException ! Only in those cases where the user's
direct action has led to the problem—such as supplying invalid input to the application—is
the user likely to be able take some appropriate corrective or avoiding action the next time.
Programs that print inappropriate error messages are more likely to annoy their users rather
than achieve a useful outcome. Therefore, except in a very limited set of circumstances, notify-
ing the user is not a general solution to the problem of error reporting.
Notifying the client object
A radically different approach from those we have discussed so far is for the server object to
feedback an indication to the client object when something has gone wrong. There are two main
ways to do this:
A server can use a non- void return type of a method to return a value that indicates either
success or failure of the method call.
A server can throw an exception if something goes wrong. This introduces a new feature of
Java that is also found in some other programming languages. We shall describe this feature
in detail in Section 12.4.
Both techniques have the benefit of encouraging the programmer of the client to take into
account that a method call could fail. However, only the decision to throw an exception will
actively prevent the client's programmer from ignoring the consequences of method failure.
The first approach is easy to introduce to a method that would otherwise have a void return
type, such as removeDetails . If the void type is replaced by a boolean type, then the
method can return true to indicate that the removal was successful and false to indicate that
it failed for some reason (Code 12.3).
Code 12.3
A boolean return type
to indicate success or
* Remove the entry with the given key from the address book.
* The key should be one that is currently in use.
* @param key One of the keys of the entry to be removed.
Search WWH ::

Custom Search