Skip to content

Latest commit

 

History

History
28 lines (19 loc) · 2 KB

5566.md

File metadata and controls

28 lines (19 loc) · 2 KB

Back to questions

Solution to 5566: Exception-throwing stacks

See code at solutions/code/tutorialquestions/question5566

It is really the programmer's responsibility to ensure that he/she does call pop on an empty stack. Thus in this case an uncaught exception should be thrown. In the solution, I have defined an exception class for this purpose: StringStackUnsupportedPopException. This exception class extends Java's existing UnsupportedOperationException, a class used to capture all kinds of exceptions related to unsupported operations. UnsupportedOperationException extends RuntimeException, i.e., it is uncaught. Thus StringStackUnsupportedPopException is also uncaught.

As for the case where the stack is full, the decision as to what sort of exception should be thrown is not clear cut. On one hand, we could argue that the exception should be caught because the programmer does not know from the StringStack interface what the maximum stack size is, and thus cannot prevent the stack becoming full simply through good programming. On the other hand, we might argue that the exception should be an error because, like a call stack overflow, little can be done to recover from this problem. It does not seem sensible to make this exception uncaught.

In the solution, I have defined a class, StringStackFailedPushError, that extends Error.

Because the string stack-related exception and error I have defined are uncaught, they do not need to be declared in the StringStack interface. Look at the pop methods in StringStackArray and StringStackList to see when a StringStackUnsupportedPopException is thrown. Observe that the first few lines of pop are identical in each class. It would be best practice to extract this commonality into a single place -- think about how you would achieve this.

A StringStackFailedPushError can be thrown by the push method in String``StackArray.

See Demo for an example of these exceptions in action.