Java Reference
In-Depth Information
readData(in);
}
finally
{
reader.close();
}
return data;
}
516
517
Note how the finally clause ensures that the file is closed even when an exception
occurs.
Also note that the throws specifier of the readFile method need not include the
FileNotFoundException class because it is a subclass of IOException .
Next, here is the readData method of the DataSetReader class. It reads the
number of values, constructs an array, and calls readValue for each data value.
private void readData(Scanner in) throws
BadDataException
{
if (!in.hasNextInt())
throw new BadDataException("Length expected");
int numberOfValues = in.nextInt();
data = new double [numberOfValues];
for (int i = 0; i < numberOfValues; i + +)
readValue(in, i);
if (in.hasNext())
throw new BadDataException("End of file
expected");
}
This method checks for two potential errors. The file might not start with an integer,
or it might have additional data after reading all values.
However, this method makes no attempt to catch any exceptions. Plus, if the
readValue method throws an exceptionȌwhich it will if there aren't enough
values in the fileȌthe exception is simply passed on to the caller.
Here is the readVal ue method:
private void readValue(Scanner in, int i) throws
BadDataException
{
Search WWH ::




Custom Search