Java Reference
In-Depth Information
case 4:
System.out.println(“File corrupted”);
break;
default:
System.out.println(“Error”);
}
} else {
// file loaded OK, continue with program
}
This code tries to load a file with a method call to loadTextFile() , which presumably
has been defined elsewhere in the class. The method returns an integer that indicates
whether the file loaded properly (a value of 1 ) or an error occurred (anything other
than 1 ).
Depending on the error that occurs, the program uses a switch statement to address it.
The end result is an elaborate block of code in which the most common circumstance—a
successful file load—can be lost amid the error-handling code. This is the result of han-
dling only one possible error. If other errors take place later in the program, you might
end up with more nested if - else and switch - case blocks.
As you can see, error management would become a major problem after you start creat-
ing larger programs. Different programmers designate special values for handling errors,
and they might not document them well if at all.
Code to manage these kinds of errors can often obscure the program's original intent,
making the class difficult to read and maintain.
Finally, if you try to deal with errors in this manner, there's no easy way for the compiler
to check for consistency the way it can check to make sure that you called a method with
the right arguments.
Although the previous example uses Java syntax, you don't ever have to deal with errors
that way with the Java language. There's a better technique to deal with exceptional cir-
cumstances in a program: the use of a group of classes called exceptions.
Exceptions include errors that could be fatal to your program as well as other unusual
situations. By managing exceptions, you can manage errors and possibly work around
them.
7
Errors and other conditions in Java programs can be much more easily managed through
a combination of special language features, consistency checking at compile time, and a
set of extensible exception classes.
Search WWH ::




Custom Search