Java Reference
In-Depth Information
Figure 11.3
Output of the CatchDemo program when no exception occurs.
The previous statements demonstrate three catch blocks, but you can have
any number of them after a single try. If an exception occurs in the protected
code, the exception is thrown to the first catch block in the list. If the data type
of the exception thrown matches ExceptionType1 , it gets caught there. If not, the
exception passes down to the second catch statement. This continues until the
exception either is caught or falls through all catches, in which case the current
method stops execution and the exception is thrown down to the previous
method on the call stack.
In the readOneByte() method of the MyFileUtilities class, there are two try/
catch blocks: one for the FileNotFoundException and one for the IOException.
I created two try/catch blocks to demonstrate both the flow of control of
exceptions and how to use try and catch. However, I would typically write a
single try block that has two catch blocks, as shown in the readOneByte()
method of the following MyFileUtilities2 class.
import java.io.*;
public class MyFileUtilities2
{
private String fileName;
public MyFileUtilities2(String name)
{
fileName = name;
}
public byte readOneByte()
{
FileInputStream file = null;
byte x = -1;
try
{
System.out.println(“Opening file for reading...”);
file = new FileInputStream(fileName);
System.out.println(“Just opened file: “ + fileName);
System.out.println(“Reading one byte from file...”);
x = (byte) file.read();
}catch(FileNotFoundException f)
{
System.out.println(“** Could not find “
Search WWH ::




Custom Search