TheAlgorithms/Java · error · IllegalStateException
Stack is empty, cannot pop element
Error message
Stack is empty, cannot pop element
What it means
Thrown by StackArray.pop() when the stack holds no elements. pop() reads stackArray[top--], so on an empty stack top is -1 and the index would be invalid. The IllegalStateException guards a precondition violation: removing an element that does not exist.
Source
Thrown at src/main/java/com/thealgorithms/datastructures/stacks/StackArray.java:69
@Override
public void push(T value) {
if (isFull()) {
resize(maxSize * 2);
}
stackArray[++top] = value;
}
/**
* Removes and returns the element from the top of the stack. Shrinks the stack if
* its size is below a quarter of its capacity, but not below the default capacity.
*
* @return the element removed from the top of the stack
* @throws IllegalStateException if the stack is empty
*/
@Override
public T pop() {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty, cannot pop element");
}
T value = stackArray[top--];
if (top + 1 < maxSize / 4 && maxSize > DEFAULT_CAPACITY) {
resize(maxSize / 2);
}
return value;
}
/**
* Returns the element at the top of the stack without removing it.
*
* @return the top element of the stack
* @throws IllegalStateException if the stack is empty
*/
@Override
public T peek() {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty, cannot peek element");View on GitHub (pinned to fdfb9a395b)
Solutions
- Check isEmpty() before every pop().
- Drive pop loops with while (!isEmpty()) instead of a fixed iteration count.
- If an empty pop is an expected branch, catch IllegalStateException and break.
- Audit caller logic for unbalanced push/pop counts.
Example fix
// before
for (int i = 0; i < n; i++) {
T v = stack.pop();
}
// after
while (!stack.isEmpty()) {
T v = stack.pop();
} Defensive patterns
Strategy: validation
Validate before calling
while (!stack.isEmpty()) {
T v = stack.pop();
} Prevention
- Drive pop loops with isEmpty() rather than a counter.
- Keep push/pop counts balanced.
- Verify stack state before reuse.
When it happens
Trigger: Calling pop() on a freshly constructed StackArray (top==-1). Calling pop() more times than push(). Popping inside a loop controlled by an external count rather than isEmpty().
Common situations: Unbalanced push/pop in evaluation loops. Reusing a stack across operations without verifying state. Off-by-one loop termination causing an extra pop after drain.
Related errors
- Cannot pop from an empty stack.
- Cannot peek from an empty stack.
- Stack is empty, cannot peek element
- Empty stack. Nothing to pop
- Empty stack. Nothing to peek
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/777902ab33c0278b.
Report an issue: GitHub.