Java Reference
In-Depth Information
+ fileName + “ **”);
f.printStackTrace();
return -1;
}catch(IOException i)
{
System.out.println(“** Error reading one byte **”);
i.printStackTrace();
return -1;
}
System.out.println(“Just read “ + x);
return x;
}
}
With multiple catch blocks, the order in which the catch blocks are listed
is the order they are checked when an exception occurs. This has an
important side effect that I discuss in detail in the sidebar titled Catching
Exceptions and Polymorphism .
Notice in the MyFileUtilities2 class that all the statements involved with
opening and reading the file appear in the same try block. This makes the code
more readable in my opinion, yet the result of the method is identical to the
one in the MyFileUtilities program.
The following CatchDemo2 program invokes readOneByte() in MyFile-
Utilities2 by using a file that does not exist, thereby generating a FileNot-
FoundException at the following statement:
file = new FileInputStream(fileName);
Study the CatchDemo2 program and try to determine its output, which is
shown in Figure 11.4. Compare this to the output of the CatchDemo program
in Figure 11.2.
public class CatchDemo2
{
public static void main(String [] args)
{
System.out.println(“Instantiating a MyFileUtilities2
object...”);
MyFileUtilities2 util = new MyFileUtilities2(args[0]);
System.out.println(“Invoking readOneByte() method...”);
System.out.println(util.readOneByte());
}
}
Search WWH ::




Custom Search