Java Reference
In-Depth Information
catch(Exception e) {
System.out.println("Error: " + e);
String phone = details.getPhone();
The exception has been caught and reported, but no account has been taken of the fact that it is
probably incorrect just to carry on regardless.
Java's try statement is the key to supplying an error-recovery mechanism when an exception
is thrown. Recovery from an error will usually involve taking some form of corrective action
within the catch block and then trying again. Repeated attempts can be made by placing the
try statement in a loop. An example of this approach is shown in Code 12.18, which is an
expanded version of Code 12.9. The efforts to compose an alternative filename could involve
trying a list of possible folders, for instance, or prompting an interactive user for different
Code 12.18
An attempt at error
// Try to save the address book.
boolean successful = false ;
int attempts = 0;
do {
try {
successful = true ;
catch (IOException e) {
System.out.println( "Unable to save to " + filename);
if (attempts < MAX_ATTEMPTS) {
filename = an alternative file name;
} while (!successful && attempts < MAX_ATTEMPTS);
if (!successful) {
Report the problem and give up;
Although this example illustrates recovery for a specific situation, the principles it illustrates
are more general:
Anticipating an error, and recovering from it, will usually require a more complex flow of
control than if an error cannot occur.
The statements in the catch block are key to setting up the recovery attempt.
Recovery will often involve having to try again.
Successful recovery cannot be guaranteed.
There should be some escape route from endlessly attempting hopeless recovery.
Search WWH ::

Custom Search