In the pop
method of java.util.Stack
, it throws an EmptyStackException
if the Stack is empty. But the remove
method of java.util.Queue
(which is similar to pop
in the Stack
class) instead throws a NoSuchElementException
. Why is there this inconsistency in Java?
The Stack
class is a legacy class from the Java 1.0 days, prior to the introduction of the collections framework. Its interface has to be backwards compatible ... and that is how it was designed.
By contrast, the Queue
interface was introduced in the Java 1.5 revision of the collections framework. By that time, the NoSuchElementException
had been chosen by the designers as the best way to express this kind of error condition1.
Note that NoSuchElementException
could have been used in Stack
since both classes existed in Java 1.0, but clearly, the designers had other ideas back then2.
So this is just a historical anomaly that has arisen due to the way that the Java APIs have evolved. It cannot be fixed without breaking binary compatibility for existing applications that use the Stack
class.
1 - You may disagree with that, but you asked why, and this is why.
2 - Or maybe they were just too rushed to get the API design correct. The Java 1.0 release was made under extreme pressure to meet a perceived market opportunity. A few mistakes were made and could not be corrected in time. Other examples include the Enumeration
API, the deprecated Thread
methods, the Hashtable
and Vector
classes, StringBuffer
and so on. But once Java 1.1 was released, it was too late.
The Stack class was there first. In the Javadoc it says "since JDK 1". It defined its own exception type because … it could.
At that same time, the NoSuchElementException already existed, but the Java collections framework didn't exist yet. Therefore it was not yet common to use that exception widely. It was "just one of the predefined exception" types.
The collections framework was added in Java 1.2, and it could not use the StackEmptyException
because its name restricts it to be used only with stacks.
At that point, the old Stack class could not be modified anymore since that would have broken existing code. Java has been successful of being backwards compatible over decades, and the exception inconsistency is one sign of this compatibility.
To get an official answer, you could look at the code. It says:
@author Jonathan Payne
If it's really important for you to know, you can contact him directly and ask him whether he remembers what he did 20 years ago. Maybe he does. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With