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
- Check isEmpty() before each pop(), especially in matching algorithms.
- Catch StackException around pop() and treat empty as a normal outcome.
- 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
- Check isEmpty() before every pop(), especially in matching algorithms (isValid, minAddToMakeValid).
- In bracket matching, pop only when a matching opener exists on the stack.
- Track push count vs pop count in loops.
- Drain with while (!stack.isEmpty()) instead of fixed counts.
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
- Cannot peek from an empty stack!!
- name is kunal
- Queue is empty
- Queue is empty
- Removing from an empty heap!
AI-assisted analysis of kunal-kushwaha/DSA-Bootcamp-Java@6bc4d8bf8a (2026-08-31).
Data as JSON: /api/errors/11043db69ee1c8f1.
Report an issue: GitHub.