Java Reference
In-Depth Information
Exceptions
Programmers in any language endeavor to write bug-free programs, programs that never
crash, programs that can handle any circumstance with grace and recover from unusual
situations without causing a user any undue stress. Good intentions aside, programs like
this don't exist.
In real programs, errors occur because programmers didn't anticipate possible problems,
didn't test enough, or encountered situations out of their control—bad data from users,
corrupt files that don't have the correct data in them, network connections that don't con-
nect, hardware devices that don't respond, sun spots, gremlins, and so on.
In Java, the strange events that might cause a program to fail are called exceptions. Java
defines a number of language features that deal with exceptions:
How to handle exceptions in your code and recover gracefully from potential
problems
n
How to tell Java and users of your classes that you're expecting a potential
exception
n
How to create an exception if you detect one
n
How your code is limited, yet made more robust by exceptions
n
With most programming languages, handling error conditions requires much more work
than handling a program that is running properly. It can require a confusing structure of
conditional statements to deal with errors that might occur.
As an example, consider the following statements that could be used to load a file from
disk. File input and output can be problematic because of a number of different circum-
stances such as disk errors, file-not-found errors, and the like. If the program must have
the data from the file to operate properly, it must deal with all these circumstances before
continuing.
Here's the structure of one possible solution:
int status = loadTextFile();
if (status != 1) {
// something unusual happened, describe it
switch (status) {
case 2:
System.out.println(“File not found”);
break;
case 3:
System.out.println(“Disk error”);
break;
 
Search WWH ::




Custom Search