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

  1. Wrap the call: if (!queue.isEmpty()) { queue.remove(); }.
  2. Catch Exception around remove() and handle gracefully.
  3. 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

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


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