Java Reference
In-Depth Information
( throws clause) During program execution, various things can happen—for example,
division by zero or inputting a letter for a number. If such things happen, the system would
not tolerate it. In such cases, we say that an exception has occurred. If an exception occurs
in a method, then the method should either handle the exception or throw it for the
calling environment to handle. If an input file does not exist, the program throws a
FileNotFoundException . Similarly, if an output file cannot be created or accessed,
the program throws a FileNotFoundException . For the next few chapters, we will not
be concerned with the handling of the exceptions; we will simply throw the exceptions.
Because we do not need the method main to handle the FileNotFoundException ,we
will include a command in the heading of the method main to throw the
FileNotFoundException . Chapter 11 describes exception handling.
3
In skeleton form, a program that uses file I/O is usually of the following form:
import java.io.*;
import java.util.*;
//Add additional import statements as needed
public class ClassName
{
//Declare appropriate variables
public static void main(String[] args)
throws FileNotFoundException
{
//Create and associate the stream objects
Scanner inFile =
new Scanner( new FileReader("prog.dat"));
PrintWriter outFile = new PrintWriter("prog.out");
//Code for data manipulation
//Close file
inFile.close();
outFile.close();
}
}
The remainder of this chapter gives two programming examples—one illustrates dialog
boxes for input/output; the other illustrates file input/output.
 
Search WWH ::




Custom Search