Java Reference
In-Depth Information
import java.io.*;
public class Lazy
{
private String fileName;
public Lazy(String name)
{
fileName = name;
}
public byte readOneByte()
{
FileInputStream file = null;
byte x = -1;
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();
System.out.println(“Just read “ + x);
return x;
}
}
The compiler is telling us that the readOneByte() method either has to catch
the FileNotFoundException that can occur from the statement new FileInput-
Stream() or declare it. The compiler is saying the same about the IOException
that can occur from the read() statement.
You have seen how to handle an exception using a try/catch block. Now,
let's look at our other option in the Handle or Declare Rule: declaring an
exception.
Declaring Exceptions
If a method does not handle a checked exception, the method must declare it
using the throws keyword. The throws keyword appears at the end of a
method's signature. For example, the following method declares that it throws
a RemoteException:
public void deposit(double amount) throws RemoteException
A method can declare that it throws more than one exception, in which case
the exceptions are declared in a list separated by commas. For example, the fol-
lowing method declares that it throws a RemoteException and an Insufficient-
FundsException:
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException
Search WWH ::




Custom Search