next up previous
Next: Propagation of exceptions Up: Unit 09 Previous: The getMessage method

Example of exception handling

Write a Java program that prints the maximum of the sequence of non negative integer values that are stored on the file data.txt.

We first concentrate on the problem without considering exceptions.

import java.io.*;

public class MaximumWithoutExceptions {
  public static void main (String args[]) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader("data.txt"));
            // could generate FileNotFoundException (checked)
    int max = -1;

    String line = br.readLine();
            // could generate IOException (checked)
    while (line != null) {
      int n = Integer.parseInt(line);
          // could generate NumberFormatException (unchecked)
      if (n > max) max = n;
      line = br.readLine();
          // could generate IOException (checked)
    }
    System.out.println("Maximum = " + max);
  }
}

Let us now consider exceptions.

import java.io.*;

public class MaximumWithExceptions {
  public static void main (String args[]) {
    try {
      BufferedReader br = new BufferedReader(new FileReader("data.txt"));
                // could generate FileNotFoundException (checked)
      int max = -1;

      String line = br.readLine();
                // could generate IOException (checked)
      while (line != null) {
        int n = Integer.parseInt(line);
                // could generate NumberFormatException (unchecked)
        if (n > max) max = n;
        line = br.readLine();
                // could generate IOException (checked)
      }
      if (max == -1)
         throw new Exception("File empty or all numbers < 0");
      else
         System.out.println("Maximum = " + max);
      }
    catch (FileNotFoundException e) {
       System.out.println("The file does not exist.");
    }
    catch (IOException e) {
       System.out.println("The file cannot be read.");
    }
    catch (NumberFormatException e) {
       System.out.println("The file contains non numeric data.");
    }
    catch (Exception e) {
       System.out.println(e.getMessage());
    }
  }
}

If the file contains alphanumeric data that cannot be converted to integer values, the first program would generate the following error message:

Exception in thread "main" java.lang.NumberFormatException: For input string: "pippo"
  at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
  at java.lang.Integer.parseInt(Integer.java:468)
  at java.lang.Integer.parseInt(Integer.java:518)
  at MaximumWithoutExceptions.main(MaximumWithoutExceptions.java:12)

The second program, instead, would handle the exception and print:

The file contains non numeric data.


next up previous
Next: Propagation of exceptions Up: Unit 09 Previous: The getMessage method