kunal-kushwaha/DSA-Bootcamp-Java · error · Exception
Queue is empty
Error message
Queue is empty
What it means
CircularQueue.remove() throws a checked java.lang.Exception when the queue is empty, because there is no element to dequeue. The throws clause forces callers to handle the underflow condition at compile time.
Source
Thrown at lectures/19-stacks-n-queues/code/src/com/kunal/CircularQueue.java:39
}
public boolean isEmpty() {
return size == 0;
}
public boolean insert(int item) {
if (isFull()) {
return false;
}
data[end++] = item;
end = end % data.length;
size++;
return true;
}
public int remove() throws Exception {
if (isEmpty()) {
throw new Exception("Queue is empty");
}
int removed = data[front++];
front = front % data.length;
size--;
return removed;
}
public int front() throws Exception{
if (isEmpty()) {
throw new Exception("Queue is empty");
}
return data[front];
}
public void display() {
if (isEmpty()) {
System.out.println("Empty");View on GitHub (pinned to 6bc4d8bf8a)
Solutions
- Guard with if (!queue.isEmpty()) before calling remove().
- Catch Exception around remove() and treat empty as a normal condition.
- Use queue.size()/isEmpty() in loop conditions instead of a fixed count.
Example fix
// before
int val = queue.remove();
// after
if (!queue.isEmpty()) {
int val = queue.remove();
} Defensive patterns
Strategy: validation
Validate before calling
if (!cq.isEmpty()) {
int val = cq.remove();
} Try / catch
try {
int val = cq.remove();
} catch (Exception e) {
// queue was empty — treat as normal, e.g. break the consume loop
} Prevention
- Check isEmpty() before every dequeue.
- Drive consume loops off queue.size(), not fixed counts.
- Never assume a producer has already enqueued before consuming.
- Treat empty-queue as an expected state, not a crash.
When it happens
Trigger: Calling remove() on a CircularQueue where size == 0 (isEmpty() true): dequeuing more times than insert() was called, or removing before any insert.
Common situations: Consumer loops draining a queue faster than producers fill it; off-by-one loop bounds consuming one extra element; calling remove() on a freshly constructed queue.
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/b6a62d5acaeebe28.
Report an issue: GitHub.