Java Reference
In-Depth Information
//Read failed
return;
}finally
{
//Close the file.
}
If no IOException occurs in this try/catch/finally block, the catch block is
skipped and the finally block executes. If an IOException does occur, the catch
block executes and a return statement is reached. The method will return, but
before it does, the finally block will execute.
I want you to study the readOneByte() method in the following MyFile-
Utilities3 class. The try/catch block contains a finally block that closes the file
opened in the try block.
import java.io.*;
public class MyFileUtilities3
{
private String fileName;
public MyFileUtilities3(String name)
{
fileName = name;
}
public byte readOneByte() throws FileNotFoundException
{
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 “ + fileName);
throw f;
}catch(IOException i)
{
System.out.println(“Error reading one byte”);
i.printStackTrace();
return -1;
}finally
{
System.out.println(“** Inside finally block **”);
try
{
if(file != null)
{
Search WWH ::




Custom Search