kunal-kushwaha/DSA-Bootcamp-Java · error · Exception
Queue is empty
Error message
Queue is empty
What it means
CustomQueue.remove() throws a checked Exception when the queue is empty, since there is no element at data[0] to dequeue. The checked throws declaration makes callers explicitly deal with underflow.
Source
Thrown at lectures/19-stacks-n-queues/code/src/com/kunal/CustomQueue.java:36
public boolean isFull() {
return end == data.length; // ptr is at last index
}
public boolean isEmpty() {
return end == 0;
}
public boolean insert(int item) {
if (isFull()) {
return false;
}
data[end++] = item;
return true;
}
public int remove() throws Exception {
if (isEmpty()) {
throw new Exception("Queue is empty");
}
int removed = data[0];
// shift the elements to left
for (int i = 1; i < end; i++) {
data[i-1] = data[i];
}
end--;
return removed;
}
public int front() throws Exception{
if (isEmpty()) {
throw new Exception("Queue is empty");
}
return data[0];
}View on GitHub (pinned to 6bc4d8bf8a)
Solutions
- Wrap the call: if (!queue.isEmpty()) { queue.remove(); }.
- Catch Exception around remove() and handle gracefully.
- Track consumed counts against insert() counts in loops.
Example fix
// before
int item = queue.remove();
// after
while (!queue.isEmpty()) {
int item = queue.remove();
} Defensive patterns
Strategy: validation
Validate before calling
if (!queue.isEmpty()) {
int item = queue.remove();
} Try / catch
try {
int item = queue.remove();
} catch (Exception e) {
// queue underflow — skip or terminate the loop
} Prevention
- Check isEmpty() before every remove().
- Bounds-check loops that dequeue a known count of items.
- Synchronize producer/consumer assumptions or check size each iteration.
- Reset size tracking when reusing queue objects.
When it happens
Trigger: Calling remove() on a CustomQueue where isEmpty() is true: dequeuing more than insert() was called, or removing from a new queue.
Common situations: BFS/processing loops calling remove() one time too many; producer/consumer code where the consumer outruns the producer; reusing a queue after draining it without checking size.
Related errors
- Queue is empty
- Removing from an empty heap!
- Removing from empty Heap
- Cannot pop from an empty stack!!
- name is kunal
AI-assisted analysis of kunal-kushwaha/DSA-Bootcamp-Java@6bc4d8bf8a (2026-08-31).
Data as JSON: /api/errors/8e7a66577aaae852.
Report an issue: GitHub.