C SC 160 Chapter 8 topic: Exceptions
major resource: An Introduction to Object-Oriented Programming with Java, fourth edition, Wu, McGraw Hill, 2006

[ previous | schedule | next ]

Overview

Stack trace

Intercepting and handling an exception

Here is a method intended to get integer age input from user:
public int getAge() {
   String input = JOptionPane.showInputDialog(null, "Please enter your age");
   int age = Integer.parseInt(input);
   return age;
}
Suppose the user enters non-numeric data by mistake, such as "we" instead of "23" (one keyboard row too low)? The call to Integer.parseInt(input) will result in an exception and program will terminate. Not very friendly.

Here is a version that will catch this exception and repeat the request until a valid integer is entered:

public int getAge() {
   String input;
   int age;
   input = JOptionPane.showInputDialog(null, "Please enter your age");
   while (true) {
      try {
         age = Integer.parseInt(input);
         return age;
	   } catch (NumberFormatException e) {
         input = JOptionPane.showInputDialog(null, 
                        "'"+input+"' is not a valid age.  Please re-enter.");
      }
   }
}
The exception strategy works like this: If the exception occurs, the user is prompted to re-enter then control goes to the next loop iteration to convert again.

Programmer-generated Exceptions

This solution can be improved further by checking to be sure the age is not negative. Here are three alternatives, two of which use a programmer-generated exception with the throw statement:
  1. Replace return age; with an if-then-else that tests (age >= 0). If true, then return age, else do a JOptionPane.showInputDialog() with the error message and to get another value.
  2. Just before return age;, add an if-then statement that tests (age < 0). If true, then throw new Exception();. In addition, change the catch parameter to be of type Exception so it will catch either the system-generated NumberFormatException or the programmer-generated exception (Exception is a superclass of NumberFormatException).
  3. (Best Solution) Code the if-then as described in alternative 2. Then add a second catch block having parameter of type Exception to handle the programmer-generated exception.
The third solution would look something like this, with additional code in bold:
public int getAge() {
   String input;
   int age;
   input = JOptionPane.showInputDialog(null, "Please enter your age");
   while (true) {
      try {
         age = Integer.parseInt(input);
         if (age < 0) {
             throw new Exception();
         }
         return age;
	   } catch (NumberFormatException e) {
         input = JOptionPane.showInputDialog(null, 
                        "'"+input+"' is not a valid age.  Please re-enter.");
      } catch (Exception e) {
          input = JOptionPane.showInputDialog(null,
                        "Age cannot be negative.  Please re-enter.");
      }
   }
}
Additional information about this example: It is also possible to define your own custom Exception subclass then create, throw and catch exceptions of that type.

Propagating an exception with the throws clause

You may wish to have your method avoid dealing with an exception and "pass the buck" on to the client method that called it. This is done by adding a throws clause to the method signature. Here's our same example, with throws added to original version:
public int getAge() throws NumberFormatException {
   String input = JOptionPane.showInputDialog(null, "Please enter your age");
   int age = Integer.parseInt(input);
   return age;
}
See how much easier it is to pass the buck?

Checked and Unchecked Exceptions

Java Exceptions are classified as either checked or unchecked

Example of using method that throws checked exception

The file input/output methods nearly all throw a checked exception of some sort. If you do file programming, you will have to deal with this by either catching or explicitly propagating the exception.

This method returns the value read by a FileReader object. The read() method it inherits from InputStreamReader is defined to throw IOException, which is a checked exception. Here, we choose to propagate the exception.

 public int getValue(FileReader myReader) throws IOException {
    return myReader.read();
 }
In the second example, we choose instead to catch the exception and return a -1 value. The client may interpret this as an "end of stream" and stop reading from the file. In this example it is actually better to propagate, so the client will know that an error actually occurred rather than think the end of file was reached.
 public int getValue(FileReader myReader) {
    try {
       return myReader.read();
    } catch (IOException e) {
       return -1;
    }
 }

Deciding whether to catch, explicitly propagate, or ignore the exception

Decision of what to do with an exception depends on whether it is checked or unchecked, and the "contract" between a method and its clients.

Consider your method's rights and responsibilities in its role as a supplier of a service (server):

Consider your method's responsibilities in its role as a client of other methods:
[ C SC 160 | Peter Sanderson | Math Sciences server  | Math Sciences home page | Otterbein ]

Last updated:
Peter Sanderson (PSanderson@otterbein.edu)