Java Reference
In-Depth Information
25 double [] data = reader.
readFile(filename);
26 double sum = 0 ;
27 for ( double d : data) sum = sum + d;
28 System.out.println( ÐThe sum is Ñ +
sum);
29 done = true ;
30 }
31 catch (FileNotFoundException exception)
32 {
33 System.out.println( ÐFile not found.Ñ );
34 }
35 catch (BadDataException exception)
36 {
37 System.out.println( ÐBad data: Ñ +
exception.getMessage());
38 }
39 catch (IOException exception)
40 {
41 exception.printStackTrace();
42 }
43 }
44 }
45 }
The first two catch clauses in the main method give a human-readable error report
if the file was not found or bad data was encountered. However, if another
IOException occurs, then we print the stack trace so that a programmer can
diagnose the problem.
The following readFile method of the DataSetReader class constructs the
Scanner object and calls the readData method. It is completely unconcerned
with any exceptions. If there is a problem with the input file, it simply passes the
exception to its caller.
public double[] readFile(String filename)
throws IOException, BadDataException
{
FileReader reader = new FileReader(filename);
try
{
Scanner in = new Scanner(reader);
Search WWH ::




Custom Search