Page 606 - Introduction to Programming with Java: A Problem Solving Approach
P. 606
572 Chapter 14 Exception Handling
That results in a program that compiles successfully and runs. But is it a good program? Novice program- mers often solve problems by trying something out without thoroughly thinking it through, and if it leads to reasonable results, they quickly move on. Try to resist that urge. Although the above code compiles and runs, it doesn’t behave appropriately when an IOException is thrown. Can you identify the inappropriate behavior? If an IOException is thrown, thecatchblockprintsits"File I/O error"message.Butthenitalsoprintsthe
" created."message,eventhoughnofilewascreated.Remember—justbecauseapro- gram runs, that doesn’t mean it’s right.
Here’s the preferred solution:
else
Don’t move on until you’re sure of your solution.
fileName +
{
try
{
file.createNewFile();
System.out.println(fileName + " created.");
This statement is now in a better location.
}
}
catch (IOException ioe)
{
}
System.out.println("File I/O error");
Now the program prints the “creaAtepd”amegssaoge onPlyDifFthe fiEle ins ahctualnlycreeaterd. Yeah! 14.9 The Exception Class and Its getMessage Method
So far, our examples have been relatively simple. Each try block has thrown only one type of exception. In that case, the catch logic is straightforward—catch the type of exception that’s being thrown. For cases where you have a try block that might throw more than one type of exception, the catch logic can be a bit more complicated. You have to choose between these two techniques: (1) provide a generic catch block that handles every type of exception that might be thrown, or (2) provide a sequence of specific catch blocks, one for each type of exception that might be thrown. In this section, we describe the generic-catch- block technique, and in the next section we describe the sequence-of-catch-blocks technique.
Generic catch Block
To provide a generic catch block, define a catch block with an Exception type parameter. Then, in-
side the catch block, call the Exception class’s getMessage method, like this: catch (Exception e)
{
}
System.out.println(e.getMessage());
If a catch block uses an Exception parameter, it will match all thrown exceptions. Why? Because when an exception is thrown, it looks for a catch parameter that’s either identical to the thrown exception or a superclass of the thrown exception. The Exception class is the superclass of all thrown exceptions, soallthrownexceptionsconsideranException catchparametertobeamatch.