next up previous
Next: 1.5.4 Static Type Checking Up: 1.5 Loose Ends Previous: 1.5.2 Local variables

1.5.3 Unchecked Exceptions

Some operations on data are inherently partial. For example, there is no mathematically sensible definition for the result of integer division by zero. Similarly, there is no sensible definition for the first element of an empty list. Java provides an elegant mechanism for coping with this problem. Program operations can ``throw'' a ``run-time error'' condition called an unchecked exception that aborts program execution and prints a diagnostic error message and a traceback of the pending stack of method calls. For example, attempting to divide any int by 0 generates an ArithmeticException. Exceptions are ordinary Java data objects descended from the built-in class called Exception. Unchecked exceptions are descendants of the class RuntimeException extending Exception.

In Java, any class method can ``throw'' an exception simply by executing the statement

throw e;
where e is any expression that evaluates to an object of type Exception. The classes Exception and RuntimeException both include empty constructors and constructors that a single string argument. The string argument is printed as a diagnostic message if it is provided.

The following Java code implements lists akin to those in Scheme.

abstract class FunList {

  abstract Object first();
  abstract FunList rest();

  public String toString() {
  // override the default Object.toString().
    return "(" + toStringHelp() + " )";
  }
  abstract String toStringHelp();
}

class Empty extends FunList {

  Object first() { 
    throw new ClassCastException("first requires a non-Empty Funlist"); 
  }
  FunList rest() { 
    throw new ClassCastException("rest requires a non-Empty Funlist"); 
  }

  String toStringHelp() {
    return "";
  }
}

class Cons extends FunList {
  Object first;
  FunList rest;

  Cons(Object f, FunList r) {
    first = f;
    rest = r;
    }

  Object first() {
    return first;
  }

  FunList rest() {
    return rest;
  }

  String toStringHelp() {
    return " " + first + rest.toStringHelp();
  }
}

The class ClassCastException is a built-in Java class extending RuntimeException that other built-in Java classes use to signal improper method applications where this or some other argument belongs to the wrong class.

Exception objects that do not belong to the type RuntimeException are called checked exceptions. We will discuss how they are used later in this monograph.


next up previous
Next: 1.5.4 Static Type Checking Up: 1.5 Loose Ends Previous: 1.5.2 Local variables
Robert Cartwright, Spring 1999