Exercises in this lecture   previous -- Keyboard shortcut: 'p'        Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home      

Exercise 9.4
More exceptions in class Stack


In continuation of the previous exercise, we now wish to introduce the following somewhat unconventional handling of stack exceptions:

  • If you push an element on a full stack throw half of the elements away, and carry out the pushing.
  • If you pop/top an empty stack, push three dummy elements on the stack, and do the pop/top operation after this.

With these ideas, most stack programs will be able to terminate normally (run to the end).

I suggest that you introduce yet another specialization of the stack class, which specializes Push, Pop, and Top. The specialized stack operations should handle relevant stack-related exceptions, and delegate the real work to its superclass. Thus, in the specialized stack class, each stack operation, such as Push, you should embed base.push(el) in a try-catch control structure, which repairs the stack - as suggested above - in the catch clause.


Solution