TheAlgorithms/Java · error · NoSuchElementException

Queue is empty

Error message

Queue is empty

What it means

Thrown by LinkedQueue.dequeue() as a NoSuchElementException when isEmpty() (size == 0). The linked queue cannot return a front node that does not exist, so it rejects the removal. This mirrors the standard FIFO underflow contract.

Source

Thrown at src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java:73

        if (isEmpty()) {
            front = newNode;
        } else {
            rear.next = newNode;
        }
        rear = newNode;
        size++;
    }

    /**
     * Removes and returns the element at the front of the queue.
     *
     * @return the element at the front of the queue.
     * @throws NoSuchElementException if the queue is empty.
     */
    public T dequeue() {
        if (isEmpty()) {
            throw new NoSuchElementException("Queue is empty");
        }

        T retValue = front.data;
        front = front.next;
        size--;

        if (isEmpty()) {
            rear = null;
        }

        return retValue;
    }

    /**
     * Returns the element at the front of the queue without removing it.
     *
     * @return the element at the front of the queue.
     * @throws NoSuchElementException if the queue is empty.

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Guard with isEmpty() before dequeue() and skip/wait when empty.
  2. Use size() in loop bounds so the number of dequeues never exceeds the number of enqueues.
  3. Catch NoSuchElementException when an empty queue is a valid outcome.

Example fix

// before
T v = queue.dequeue(); // throws when empty

// after
T v = null;
if (!queue.isEmpty()) {
    v = queue.dequeue();
}
Defensive patterns

Strategy: validation

Validate before calling

if (!queue.isEmpty()) {
    T v = queue.dequeue();
}

Type guard

null

Try / catch

null

Prevention

When it happens

Trigger: Calling dequeue() before any enqueue(), or calling dequeue() more times than enqueue(). Any removal past the last element throws.

Common situations: Consumer thread outpacing the producer; loop counters off by one; draining a queue after work completion with an extra pop; BFS/pipeline stages that dequeue when no input arrived.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/b3ce984d1434e943. Report an issue: GitHub.