Home CPSC 330

Exceptions Exercise

Objective

To become more familiar with exceptions.

Task

In Java, some exceptions are unchecked meaning that if you don't catch them, your code will still compile.

Others, however, are checked meaning that you must signify how your code deals with a possible exception.

For this lab, you will modify the following program that opens a file called "data.txt", and adds up all of the integers in the file and reports the sum.


import java.io.*;
import java.util.*;

public class Sum {
  public static void main(String args[]) {
    // open the file
    FileReader reader = new FileReader("data.txt");

    // make a scanner from it
    Scanner in = new Scanner(reader);

    // read all the numbers
    int sum = 0;
    while(in.hasNext()) {
      sum += in.nextInt();
    }

    // print the sum
    System.out.printf("Sum is %d.\n", sum);
  }
}

This program does not compile because of an unchecked FileNotFoundException. You will add a exception handling to the program to handle this exception. In this case your porgram should report that the input file was not found and exit.

You should also catch the InputMismatchException encountered when the input is not an integer. You should just not count these entries in the file towards the sum.


Details


Submitting

When your program works, email the code to ifinlay@umw.edu.

Copyright © 2018 Ian Finlayson | Licensed under a Creative Commons Attribution 4.0 International License.