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
- Guard with isEmpty() before dequeue() and skip/wait when empty.
- Use size() in loop bounds so the number of dequeues never exceeds the number of enqueues.
- 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
- Guard every dequeue with isEmpty().
- Keep enqueue/dequeue counts balanced in producer-consumer code.
- Return Optional from your own dequeue wrapper to force callers to handle emptiness.
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
- Queue is empty
- Queue is empty, cannot remove element
- Queue is empty, cannot peek front
- Queue is empty, cannot peek rear
- Queue is empty
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/b3ce984d1434e943.
Report an issue: GitHub.