Consider the StringStack
interface and ArrayStringStack
and ListStringStack
implementing classes you
created in question 1486. (Note: if you have completed question 2ffc then feel free to adapt this question to work with the
generic versions of the string stack classes.)
Recall that you were asked to implement the pop()
operation so that if pop()
is called on an empty stack, nothing
happens. Similarly, for ArrayStringStack
, which had maximum stack size of 100, your push()
operation was supposed
to do nothing in the case that the maximum stack size had been reached.
A better solution to these extreme cases is to throw an exception. Adapt your string stack classes and interfaces so that appropriate
exceptions (which you may wish to define yourself) are thrown by push()
and pop()
when a full and empty
stack is encountered, respectively. Decide whether these exceptions should be caught exceptions, runtime exceptions
or errors. Explain your choice, and the reason behind any changes you have to make to your string stack classes and/or interface.
Write a demonstration program that manipulates stacks in a manner that will cause these exceptions to be thrown. Your program should
use try
and catch
to intercept these exceptions and display appropriate error messages.
There are some hints for this question at the end.
Hints: Popping an empty stack (respectively pushing on to a full stack) is reminiscent of accessing an array out of bounds: this is not
an error, as if the problem occurs it is the programmer's fault. This problem should be checked for at runtime, but it would be extremely painful to require an application
to explicitly catch such stack exceptions each time a stack operation is invoked. Thus the exceptions should not be caught. Like ArrayIndexOutOfBoundsException
they should therefore be runtime exceptions.
Writing new classes for these stack exceptions provides maximum flexibility: it allows you to catch and handle these specific kinds of exception without
necessarily catching other exceptions which you would prefer to throw. However, java.util
already has an exception that may be suitable
for the case where a stack is empty.