next up previous
Next: 1.11.5 Name and Method Up: 1.11 Loose Ends Previous: 1.11.3 Casts and Static

  
1.11.4 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.

In the IntList program in Section 1.6.2 and the CompList program in Section 1.7.4, we used instances of the NoSuchElementException class to signal a run-time error and abort program execution. NoSuchElementException is a built-in Java class in the package java.util extending RuntimeException that built-in Java classes use to abort execution of a method that tries to get an element from an empty collection of objects. Since the possible run-time errors in IntList and CompList exactly match this condition, we used this existing exception class rather than defining our own (which is very easy).

Exception objects that do not belong to the type RuntimeException are called checked exceptions. In contrast to unchecked exceptions, checked exceptions must be declared in the header of any method that throws them-directly or indirectly. Since checked exceptions are awkward to use in practice, we do not recommend using them. They cannot be completely avoided, however, because some library classes use them.

Java provides a mechanism called try-catch-finally for catching exceptions and performing corrective actions. Since we are confining our usage of exceptions to signalling coding errors, we will not discuss this mechanism further.


next up previous
Next: 1.11.5 Name and Method Up: 1.11 Loose Ends Previous: 1.11.3 Casts and Static
Corky Cartwright
2001-08-02