3.1.9 When Not to Use Exceptions3.1.8 Runtime Exceptions3.1 Exception Handling3.2 Streams and Files

3.1.9 When Not to Use Exceptions

We complete our discussion of exceptions by a word on the pragmatics of their use. In a nutshell, one should reserve exceptions for that purpose that is denoted by their name: situations that are not typical for the normal program flow. Normal and expected cases should be handled by function return values and/or transient parameters.

To demonstrate the difference, let us use the previously introduced method readInt to compute the sum of a stream of integers:

   static int readAndSum() throws InputException
   {
     int s = 0;
     while (true)
     {
       int i = readInt();
       if (Input.hasEnded()) break;
       s += i;
     }
     return s;
   }

This code clearly shows the expected flow of control, the exceptional situation that an input error has occurred is treated as an exception.

Now let us assume that a clever programmer writes a version of readInt where also the end of a file is denoted by an exception:

  public class EndOfFileException extends Exception { }

  static public int readInt()
    throws EndOfFileException, InputException
  {
    int i = Input.readInt();
    if (Input.hasEnded()) throw new EndOfFileException();
    if (!Input.isOkay()) throw new InputException(``some error'');
    return i;
  }

Now the programmer can process a stream of integers as follows:

   static int readAndSum() throws InputException
   {
     int s = 0;
     try
     {
       while (true)
       {
         int i = readInt();
         s += i;
       }
     }
     catch(EndOfFileException e)
     {
       return s;
     }
   }

This program correctly computes and returns the sum of a stream of integers. However, the expected flow of control is disguised. The program only makes sense if the input stream eventually ends and a sum is returned. Looking at the protected code block above, it seems that the program under normal circumstances would never terminate! This is because we actually expect that the EndOfFileException will eventually raised; an expected exception however is not an exception at all.


© Wolfgang Schreiner; February 3, 2005

3.1.9 When Not to Use Exceptions3.1.8 Runtime Exceptions3.1 Exception Handling3.2 Streams and Files