TheAlgorithms/Java · error · EmptyHeapException

Cannot extract from empty heap

Error message

Cannot extract from empty heap

What it means

Thrown by MinHeap.extractMin() when minHeap.isEmpty() is true at call time. extractMin reads the first element then calls deleteElement(1), so the empty guard prevents an IndexOutOfBounds on getFirst(). This is a state precondition error: the heap must contain at least one element before extraction.

Source

Thrown at src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java:200

            if (smallest == elementIndex) {
                break;
            }

            swap(elementIndex, smallest);
            elementIndex = smallest;
        }
    }

    /**
     * Extracts and returns the minimum element from the heap.
     *
     * @return HeapElement with the lowest key
     * @throws EmptyHeapException if the heap is empty
     */
    private HeapElement extractMin() throws EmptyHeapException {
        if (minHeap.isEmpty()) {
            throw new EmptyHeapException("Cannot extract from empty heap");
        }
        HeapElement result = minHeap.getFirst();
        deleteElement(1);
        return result;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void insertElement(HeapElement element) {
        if (element == null) {
            throw new IllegalArgumentException("Cannot insert null element");
        }
        minHeap.add(element);
        toggleUp(minHeap.size());
    }

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Guard every extractMin call with isEmpty(): `if (!heap.isEmpty()) { ... = heap.extractMin(); }`.
  2. Track insertion count and only extract up to that count.
  3. Propagate EmptyHeapException in your method signature and handle it at the caller.
  4. Use a while loop conditioned on `!heap.isEmpty()` instead of a fixed iteration count.

Example fix

// before
HeapElement min = heap.extractMin();

// after
if (heap.isEmpty()) {
    return null; // or handle empty case
}
HeapElement min = heap.extractMin();
Defensive patterns

Strategy: validation

Validate before calling

if (!heap.isEmpty()) {
    HeapElement min = heap.extractMin();
}

Try / catch

try {
    HeapElement min = heap.extractMin();
} catch (EmptyHeapException e) {
    // heap was empty — handle gracefully
}

Prevention

When it happens

Trigger: Calling extractMin on a freshly constructed heap with no inserts. Calling extractMin more times than insertElement. Draining the heap in a loop without checking isEmpty first.

Common situations: Processing a stream where the first batch is empty. Reusing a heap object across work units without resetting state assumptions. Misordered init logic that extracts before population.

Related errors


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