TheAlgorithms/Java · error · RuntimeException
Queue is Empty
Error message
Queue is Empty
What it means
Thrown by PriorityQueue.remove() as a RuntimeException("Queue is Empty") when isEmpty(). The method extracts the max-priority element (heap root at index 1) and re-heapifies; with nItems == 0 there is no root to return. The thrown type is the generic RuntimeException, not NoSuchElementException.
Source
Thrown at src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java:128
*/
public void insert(int value) {
// Print overflow message if the capacity is full
if (isFull()) {
throw new RuntimeException("Queue is full");
} else {
queueArray[++nItems] = value;
swim(nItems); // Swim up the element to its correct position
}
}
/**
* Dequeue the element with the max priority from PQ
*
* @return The element removed
*/
public int remove() {
if (isEmpty()) {
throw new RuntimeException("Queue is Empty");
} else {
int max = queueArray[1]; // By definition of our max-heap, value at queueArray[1] pos is
// the greatest
// Swap max and last element
int temp = queueArray[1];
queueArray[1] = queueArray[nItems];
queueArray[nItems] = temp;
queueArray[nItems--] = 0; // Nullify the last element from the priority queue
sink(1); // Sink the element in order
return max;
}
}
/**
* Checks what's at the front of the queue
*View on GitHub (pinned to fdfb9a395b)
Solutions
- Guard with isEmpty() before remove() and skip or wait when empty.
- Bound removal loops by the known insert count or by re-checking isEmpty() each iteration.
- Catch RuntimeException around remove() since the type is generic rather than a standard underflow exception.
Example fix
// before
int max = pq.remove(); // throws RuntimeException when empty
// after
int max = -1;
if (!pq.isEmpty()) {
max = pq.remove();
} Defensive patterns
Strategy: validation
Validate before calling
if (!pq.isEmpty()) {
int max = pq.remove();
} Type guard
null
Try / catch
try { int max = pq.remove(); } catch (RuntimeException e) { /* empty handling */ } Prevention
- isEmpty()-guard remove before each extraction.
- Since remove throws generic RuntimeException (not NoSuchElementException), catch Exception if you must handle it.
- Bound removal loops by the actual insert count.
When it happens
Trigger: Calling remove() on a freshly constructed PriorityQueue, or calling remove() more times than insert(). Any extraction after the heap is drained throws.
Common situations: Consumer draining the priority queue before any inserts; off-by-one loop bound; tests calling remove without seeding; callers only catching specific exception types miss the generic RuntimeException.
Related errors
- Queue is full
- Cannot extract from empty heap
- Cannot delete from empty heap
- MinPriorityQueue is empty. Cannot peek.
- MinPriorityQueue is empty. Cannot delete.
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/2a3a951485b0f6d2.
Report an issue: GitHub.