next up previous
Next: Exercises Up: Unit 10 Previous: Interrupting the propagation of

Example of exception handling when reading from a file

Write a method printIntegers() that reads integer values from a file and prints them to standard output. For those lines of the file that do not contain an integer value (e.g., they contain alphabetic characters) the program should print the string "***" and continue reading from the file.

public static void printIntegers(String filename) {
  try {  // cattura exceptions di IO
    FileReader f = new FileReader(filename);
    BufferedReader in = new BufferedReader(f);
    String line = in.readLine();
    while (line != null) {
      try { // capture NumberFormaException
        int n = Integer.parseInt(line);
        System.out.println(n);
      }
      catch(NumberFormatException e) {
        System.out.println("***");
      }
      line = in.readLine();
   }
  }
  catch (IOException e) {
    System.out.println(e.getMessage());
  }
}


next up previous
Next: Exercises Up: Unit 10 Previous: Interrupting the propagation of