Java Reference
In-Depth Information
What exceptions can be thrown? The
FileReader
constructor throws a
FileNot-FoundException
when the file does not exist, which is very
appropriate in our situation. The
close
method of the
FileReader
class can
throw an
IOException
. Finally, when the file data is in the wrong format, we will
throw a
BadDataException
, a custom checked exception class. We use a checked
exception because corruption of a data file is beyond the control of the programmer.
Who can remedy the faults that the exceptions report? Only the
main
method of the
DataAnalyzer
program interacts with the user. It catches the exceptions, prints
appropriate error messages, and gives the user another chance to enter a correct file.
ch11/data/DataAnalyzer.java
1
import
java.io.FileNotFoundException;
2
import
java.io.IOException;
3
import
java.util.Scanner;
4
5 /**
6
This program reads a file containing numbers and analyzes its
contents.
7
If the file doesn't exist or contains strings that are not numbers, an
8
error message is displayed.
9 */
10
public class
DataAnalyzer
11 {
12
public static void
main(String[] args)
13 {
14 Scanner in =
new
Scanner(System.in);
15 DataSetReader reader =
new
DataSetReader();
16
17
boolean
done =
false
;
18
while
(!done)
19 {
20
try
21 {
22 System.out.println(
ÐPlease enter the
file name: Ñ
);
23 String filename = in.next();
24
515
516