next up previous index
Next: Code and Demonstration Up: Stacks Previous: Demonstration   Index


Note on Exceptions

For simplicity, the present DataStructures package reuses existing Java exceptions, rather than defining its own. Specifically, the exceptions used are
ArithmeticException
IllegalArgumentException
IllegalStateException
NoSuchElementException
UnsupportedOperationException
These are all subclasses of the RuntimeException class--the significance being that ``a method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during the execution of the method but not caught.''

There is some controversy concerning the use of RuntimeException rather than Exception, see for example the discussion in the Java online tutorial. It is certainly good practice to require the programmer to catch any exception which can arise for reasons beyond the programmer's control, for example when interacting with an external device, such as a keyboard, mouse, file server etc. But the view taken here is that it is fair practice to treat any exception, which careful programming can guarantee will never be thrown, to be a RuntimeException.

For example, in the previous StackDemo program, we wrote

while (!s.isEmpty()) {
    System.out.println(s.pop());
}
Since the pop method can only throw an exception when the stack is empty, the guard in the while loop ensures that this can never occur. If the exception thrown by the pop method had been declared to be only an Exception rather than a RuntimeException, it would be necessary for the client program to catch the exception by
while (!s.isEmpty()) {
    try {
        System.out.println(s.pop());
    } catch (Exception e) {
        // this cannot happen
    }
}
or for the client to state explicitly that the application as a whole throws this exception. Neither requirement seems a fair imposition on a programmer who has been provided with the means to ensure that an exception will not be thrown, and uses it.


next up previous index
Next: Code and Demonstration Up: Stacks Previous: Demonstration   Index
Peter Williams 2005-06-07