kunal-kushwaha/DSA-Bootcamp-Java · error · StackException

Cannot pop from an empty stack!!

Error message

Cannot pop from an empty stack!!

What it means

CustomStack.pop() throws a custom StackException when the stack is empty, guarding the data[ptr--] access that would otherwise read a stale slot or go out of bounds. The custom exception signals stack underflow with a clear message.

Source

Thrown at lectures/19-stacks-n-queues/code/src/com/kunal/CustomStack.java:29

    }

    public CustomStack(int size) {
        this.data = new int[size];
    }

    public boolean push(int item) {
        if (isFull()) {
            System.out.println("Stack is full!!");
            return false;
        }
        ptr++;
        data[ptr] = item;
        return true;
    }

    public int pop() throws StackException {
        if (isEmpty()) {
            throw new StackException("Cannot pop from an empty stack!!");
        }
//        int removed = data[ptr];
//        ptr--;
//        return removed;
        return data[ptr--];
    }

    public int peek() throws StackException {
        if (isEmpty()) {
            throw new StackException("Cannot peek from an empty stack!!");
        }
        return data[ptr];
    }

    public boolean isFull() {
        return ptr == data.length - 1; // ptr is at last index
    }

View on GitHub (pinned to 6bc4d8bf8a)

Solutions

  1. Check isEmpty() before each pop(), especially in matching algorithms.
  2. Catch StackException around pop() and treat empty as a normal outcome.
  3. Restructure loops to drive off stack size rather than input length alone.

Example fix

// before
int top = stack.pop();
// after
if (!stack.isEmpty()) {
    int top = stack.pop();
} else {
    // unmatched item — handle
}
Defensive patterns

Strategy: try-catch

Validate before calling

if (!stack.isEmpty()) {
    int top = stack.pop();
}

Try / catch

try {
    int top = stack.pop();
} catch (StackException e) {
    // underflow: handle unmatched/absent element
    System.out.println(e.getMessage());
}

Prevention

When it happens

Trigger: Calling pop() when isEmpty() is true: popping more times than push was called; matching algorithms like isValid/minAddToMakeValid popping on a mismatch with an empty stack; loops whose bound exceeds the pushed count.

Common situations: Bracket-matching algorithms where a closing character arrives with an empty stack; unwinding a stack after processing input without checking size; reusing a stack across iterations after it was drained.

Related errors


AI-assisted analysis of kunal-kushwaha/DSA-Bootcamp-Java@6bc4d8bf8a (2026-08-31). Data as JSON: /api/errors/11043db69ee1c8f1. Report an issue: GitHub.