Java Reference
In-Depth Information
public class DataSet
{
public void read(String filename) throws
FileNotFoundException
{
FileReader reader = new
FileReader(filename);
Scanner in = new Scanner(reader);
. . .
}
. . .
}
The throws clause in turn signals the caller of your method that it may encounter a
FileNotFoundException . Then the caller needs to make the same decisionȌ
handle the exception, or tell its caller that the exception may be thrown.
Add a throws specifier to a method that can throw a checked exception.
If your method can throw checked exceptions of different types, you separate the
exception class names by commas:
public void read (String filename)
throws IOException, ClassNotFoundException
Always keep in mind that exception classes form an inheritance hierarchy. For
example, FileNotFoundException is a subclass of IOException . Thus, if a
method can throw both an IOException and a FileNotFoundException , you
only tag it as throws IOException .
It sounds somehow irresponsible not to handle an exception when you know that it
happened. Actually, though, it is usually best not to catch an exception if you don't
know how to remedy the situation. After all, what can you do in a low-level read
method? Can you tell the user? How? By sending a message to System.out ? You
don't know whether this method is called in a graphical program or an embedded
system (such as a vending machine), where the user may never see System.out .
And even if your users can see your error message, how do you know that they can
understand English? Your class may be used to build an application for users in
another country. If you can't tell the user, can you patch up the data and keep going?
Search WWH ::




Custom Search