Yes. If a checked Exception
is not caught
then this is needed.
There are several unchecked Exception
s that might be thrown, but they need not be declared.
Here are the lines in a typical input file named dailyRobins.txt that records the number of robins seen for several days in Spring.
3 6 12 17 14 4 32 23 19
Here are some runs of the program. First, a file containing the above data:
C:\JavaSource>java SumFileData Input file name: dailyRobins.txt Sum = 130
Next, a mis-named file:
C:\JavaSource>java SumFileData Input file name: dailyCrows.txt Exception in thread "main" java.io.FileNotFoundException: dailyCrows.txt (The system cannot find the file specified) at java.io.FileInputStream.open0(Native Method) at java.io.FileInputStream.open(Unknown Source) at java.io.FileInputStream.(Unknown Source) at java.util.Scanner. (Unknown Source) at SumFileData.main(SumFileData.java:20)
Finally, a file with some non-intger data:
C:\JavaSource>java SumFileData
Input file name:
dailyRobins.txt
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at SumFileData.main(SumFileData.java:24)
In the last run the data file had a line that could not be parsed as an int
.
Would it work if the input file contained the following?
3 6 12 17 14 4 32 23 19