TheAlgorithms/Java · error · IllegalStateException

Cannot pop from an empty stack.

Error message

Cannot pop from an empty stack.

What it means

Thrown by NodeStack.pop() when the stack contains no elements. NodeStack is a generic linked-list-backed stack; pop() dereferences head.data to retrieve the top item, so calling it on an empty stack would produce a NullPointerException without this guard. The IllegalStateException signals a logic error in the caller — popping more times than you pushed.

Source

Thrown at src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java:60

     *
     * @param item the item to be pushed onto the stack
     */
    public void push(Item item) {
        Node newNode = new Node(item);
        newNode.previous = head;
        head = newNode;
        size++;
    }

    /**
     * Removes and returns the item at the top of the stack.
     *
     * @return the item at the top of the stack, or {@code null} if the stack is empty
     * @throws IllegalStateException if the stack is empty
     */
    public Item pop() {
        if (isEmpty()) {
            throw new IllegalStateException("Cannot pop from an empty stack.");
        }
        Item data = head.data;
        head = head.previous;
        size--;
        return data;
    }

    /**
     * Returns the item at the top of the stack without removing it.
     *
     * @return the item at the top of the stack, or {@code null} if the stack is empty
     * @throws IllegalStateException if the stack is empty
     */
    public Item peek() {
        if (isEmpty()) {
            throw new IllegalStateException("Cannot peek from an empty stack.");
        }
        return head.data;

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Guard every pop() call with an isEmpty() check before invoking it.
  2. Track the expected number of elements externally and only pop when count > 0.
  3. If pop() legitimately may find an empty stack, catch IllegalStateException at the call site.
  4. Audit the calling code for unbalanced push/pop logic.

Example fix

// before
while (true) {
    Item x = stack.pop();
    process(x);
}
// after
while (!stack.isEmpty()) {
    Item x = stack.pop();
    process(x);
}
Defensive patterns

Strategy: validation

Validate before calling

if (!stack.isEmpty()) {
    Item top = stack.pop();
} else {
    // handle empty case
}

Prevention

When it happens

Trigger: Calling pop() on a freshly constructed NodeStack (head==null). Calling pop() more times than push() was called. Calling pop() after a prior pop() already emptied the stack.

Common situations: Unbalanced push/pop in expression-evaluation or DFS traversal code. Popping in a loop without an isEmpty() check. Reusing a stack object across multiple operations without resetting or checking its state.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/276dc4986f16d197. Report an issue: GitHub.