next up previous
Next: Name and Method Overloading Up: Loose Ends Previous: Casts and Static Type

Exceptions as Errors

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 sequence. 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 list, called a traceback, of the stack of pending 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 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 a zero-ary constructor and a unary constructor. The latter takes an error message String as an argument. The string argument is printed as a diagnostic message if it is provided.

The following Java code implements ``functional'' lists of objects:

abstract class List {

  abstract Object first();
  abstract List rest();

  abstract String toStringHelp();
  // List -> String without enclosing parentheses and leading blanks

class Empty extends List {

  Object first() { 
    throw new 
      ClassCastException("first requires a non-Empty List"); 
  List rest() { 
    throw new 
      ClassCastException("rest requires a non-Empty List"); 
  public String toStringHelp() { return "()"; }
  String toStringHelp() { return ""; }

class Cons extends List {
  Object first;
  List rest;

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

  Object first() { return first; }

  List rest() { return rest; }

  public String toString() { return "(" + first + rest.toStringHelp() + ")"; }
  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: Name and Method Overloading Up: Loose Ends Previous: Casts and Static Type
Corky Cartwright 2004-02-05