Java Reference
In-Depth Information
CHAPTER
12 Handling errors
Main concepts discussed in this chapter:
defensive programming
exception throwing and handling
error reporting
basic file processing
Java constructs discussed in this chapter:
TreeMap, TreeSet, SortedMap, assert, exception, throw, throws,
try, catch, File, FileReader, FileWriter, Path, Scanner, stream
In Chapter 7, we saw that logical errors in programs are harder to spot than syntactic errors
because a compiler cannot give any help with logical errors. Logical errors arise for several
reasons, which may overlap in some situations:
The solution to a problem has been implemented incorrectly. For instance, a problem involv-
ing generating some statistics on data values might have been programmed to find the mean
value rather than the median value (the “middle” value).
An object might be asked to do something it is unable to. For instance, a collection object's
get method might be called with an index value outside the valid range.
An object might be used in ways that have not been anticipated by the class designer,
leading to the object being left in an inconsistent or inappropriate state. This often hap-
pens when a class is reused in a setting that is different from its original one, perhaps
through inheritance.
Although the sort of testing strategies discussed in Chapter 7 can help us identify and eliminate
many logical errors before our programs are put to use, experience suggests that program failures
will continue to occur. Furthermore, even the most thoroughly tested program may fail as a result
of circumstances beyond the programmer's control. Consider the case of a web-browser asked to
display a web page that does not exist or a program that tries to write data to a disk that has no more
space left. These problems are not the result of logical programming errors, but they could easily
cause a program to fail if the possibility of their arising has not been taken into account.
In this chapter, we look at how to anticipate potential errors and how to respond to error situa-
tions as they arise during the execution of a program. In addition, we provide some suggestions
 
Search WWH ::




Custom Search