TheAlgorithms/Java · error · EmptyHeapException

Cannot delete from empty heap

Error message

Cannot delete from empty heap

What it means

Thrown by MinHeap.deleteElement(int) when minHeap.isEmpty() is true at call time. Before validating the index, the method checks emptiness because accessing the last element would otherwise fail. This is the empty-state sibling of the extractMin guard.

Source

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

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

    /**
     * {@inheritDoc}
     */
    @Override
    public void deleteElement(int elementIndex) throws EmptyHeapException {
        if (minHeap.isEmpty()) {
            throw new EmptyHeapException("Cannot delete from empty heap");
        }
        if ((elementIndex > minHeap.size()) || (elementIndex <= 0)) {
            throw new IndexOutOfBoundsException("Index " + elementIndex + " is out of heap range [1, " + minHeap.size() + "]");
        }

        // Replace with last element and remove last position
        minHeap.set(elementIndex - 1, minHeap.getLast());
        minHeap.removeLast();

        // No need to toggle if we just removed the last element
        if (!minHeap.isEmpty() && elementIndex <= minHeap.size()) {
            // Determine whether to toggle up or down
            if (elementIndex > 1 && getElementKey(elementIndex) < getElementKey((int) Math.floor(elementIndex / 2.0))) {
                toggleUp(elementIndex);
            } else {
                toggleDown(elementIndex);
            }
        }

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Check isEmpty() before deleteElement.
  2. Catch EmptyHeapException (it is checked) and handle the empty case gracefully.
  3. Track heap state externally and skip deletion when the count is zero.
  4. Re-examine the lifecycle: ensure inserts happen before any delete.

Example fix

// before
heap.deleteElement(idx); // may throw on empty heap

// after
if (!heap.isEmpty()) {
    heap.deleteElement(idx);
}
Defensive patterns

Strategy: try-catch

Validate before calling

if (!heap.isEmpty()) {
    heap.deleteElement(idx);
}

Try / catch

try {
    heap.deleteElement(idx);
} catch (EmptyHeapException e) {
    // nothing to delete — safe no-op
}

Prevention

When it happens

Trigger: Calling deleteElement on a heap that was never populated. Calling deleteElement after all elements have been extracted/deleted. Deleting in a loop without an emptiness guard.

Common situations: Cleanup code that tries to remove a specific element from an already-drained heap. Logic that assumes a previous insert succeeded when it did not. Reusing heap instances across operations.

Related errors


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