3.1.3 Example3.1.2 Exceptions3.1 Exception Handling3.1.4 Handling Exceptions

3.1.3 Example

We will demonstrate the use of exceptions by protecting an input operation. First we define an appropriate exception class as  

   public class InputException extends Exception
   {
     private String msg;

     public InputException(String msg)
     {
       this.msg = msg;
     }

     public String getMessage()
     {
       return msg;
     }
  }

An object of this class stores in a string a description of the error that has occurred.

We may now write a program function

   static public int readInt() throws InputException
   {
     int i = Input.readInt();
     if (Input.hasEnded()) return -1;
     if (!Input.isOkay()) throw new InputException("some error");
     return i;
   }

This program function reads an int value from the input stream and returns it as the result. However, if an input error has occurred, the method throws an InputException which contains the information whether the file has ended or another error has occurred.

We may now use the function in the following code block:

   try
   {
     int i = readInt(); if (Input.hasEnded()) return;
     int j = readInt(); if (Input.hasEnded()) return;
     int k = readInt(); if (Input.hasEnded()) return;
     System.out.println(i + " " + j + " " + k);
   }
   catch(InputException e)
   {
     System.out.println("Input error: " + e.getMessage());
   }
   System.out.println("done.");

In normal execution (i.e., if no input error occurs), three integers i, j, and k are read and printed, i.e., the output may look like:

   2 3 5
   done.

Now let us assume that during the reading of the second integer an error has occurred. The second invocation of readInt throws an InputException which is forwarded to the handler which prints the content of the exception object e which describes what kind of error has occurred. The output of the program therefore is:

   Input error: some error
   done.


© Wolfgang Schreiner; February 3, 2005

3.1.3 Example3.1.2 Exceptions3.1 Exception Handling3.1.4 Handling Exceptions