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.
Recall the following Java code that implements ``functional'' lists:
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.abstract class FunList { abstract Object getFirst(); abstract FunList getRest(); abstract String toStringHelp(); // print a list without any parentheses and leading blanks } class Empty extends FunList { Object getFirst() { throw new ClassCastException("first requires a non-Empty FunList"); } FunList getRest() { 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 getFirst() { return first; } FunList getRest() { return rest; } public String toString() { // top level call includes parentheses return "(" + first + rest.toStringHelp() + ")"; } String toStringHelp() { return " " + first + rest.toStringHelp(); } }
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.