TheAlgorithms/Java · error · EmptyHeapException

Cannot extract from an empty heap

Error message

Cannot extract from an empty heap

What it means

Thrown by MaxHeap.extractMax() when the heap is empty. extractMax reads the root and then calls deleteElement(1); with no elements there is no maximum to return. This is a checked EmptyHeapException (declared throws), so callers must handle or propagate it.

Source

Thrown at src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java:177

                largerChildIndex = 2 * elementIndex;
            }

            swap(elementIndex, largerChildIndex);
            elementIndex = largerChildIndex;

            wrongOrder = (2 * elementIndex <= maxHeap.size() && key < getElementKey(elementIndex * 2)) || (2 * elementIndex + 1 <= maxHeap.size() && key < getElementKey(elementIndex * 2 + 1));
        }
    }

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

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

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Check isEmpty() (or ensure a public equivalent) before calling extractMax.
  2. Handle the checked EmptyHeapException explicitly rather than propagating it generically.
  3. Bound the extraction loop by the known element count captured before draining.

Example fix

// before
HeapElement max = heap.extractMax();

// after
HeapElement max = null;
try {
    max = heap.extractMax();
} catch (EmptyHeapException ignored) {
    // no elements to extract
}
Defensive patterns

Strategy: try-catch

Validate before calling

// If a public isEmpty() or equivalent is available:
// if (!heap.isEmpty()) heap.extractMax();
// Otherwise rely on the checked-exception handler below.

Try / catch

try {
    HeapElement max = heap.extractMax();
} catch (EmptyHeapException e) {
    // heap empty; nothing to extract
}

Prevention

When it happens

Trigger: Calling extractMax before any insertElement; calling it more times than elements were inserted; an extraction loop with no occupancy check.

Common situations: Scheduler/job-queue drain with no pending jobs; heap sort on an empty input; test that forgot to seed.

Related errors


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