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

  1. Guard with isEmpty() before remove() and skip or wait when empty.
  2. Bound removal loops by the known insert count or by re-checking isEmpty() each iteration.
  3. 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

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


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