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

Cannot peek from an empty stack!!

Error message

Cannot peek from an empty stack!!

What it means

CustomStack.peek() throws a custom StackException when the stack is empty, because data[ptr] holds no valid element. Unlike pop(), peek does not modify the stack; the exception purely signals underflow.

Source

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

        }
        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
    }

    public boolean isEmpty() {
        return ptr == -1;
    }
}

View on GitHub (pinned to 6bc4d8bf8a)

Solutions

  1. Guard with if (!stack.isEmpty()) before peek().
  2. Catch StackException and provide a default value.
  3. Combine peek+pop into one guarded block sharing the emptiness check.

Example fix

// before
int top = stack.peek();
// after
int top = stack.isEmpty() ? -1 : stack.peek();
Defensive patterns

Strategy: validation

Validate before calling

int top = stack.isEmpty() ? -1 : stack.peek();

Try / catch

try {
    int top = stack.peek();
} catch (StackException e) {
    int top = -1; // empty-stack default
}

Prevention

When it happens

Trigger: Calling peek() on an empty stack: peeking before the first push, or after all elements were popped — e.g. top comparisons in isValid-style code once the stack is drained.

Common situations: Peek-driven comparisons ('is top greater than x') that run when no elements exist; debug/logging of the top value; iterative algorithms peeking in the loop condition without an emptiness check.

Related errors


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