TheAlgorithms/Java · error · EmptyHeapException

Cannot delete from an empty heap

Error message

Cannot delete from an empty heap

What it means

Thrown by MaxHeap.deleteElement(int) when the heap is empty. deleteElement swaps the target with the last element and removes it; with zero elements there is nothing to delete and the subsequent index check would be meaningless. This is a checked EmptyHeapException that callers must handle or declare.

Source

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

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

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

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

        // No need to toggle if we just removed the last element
        if (!maxHeap.isEmpty() && elementIndex <= maxHeap.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. Guard with an emptiness check before calling deleteElement.
  2. Handle the checked EmptyHeapException at the call site (it is often a benign 'nothing to do' case).
  3. Track the element count externally and skip deletion when it is zero.

Example fix

// before
heap.deleteElement(index);

// after
try {
    heap.deleteElement(index);
} catch (EmptyHeapException ignored) {
    // heap already empty; nothing to delete
}
Defensive patterns

Strategy: try-catch

Validate before calling

// If a public emptiness check is available, guard first:
// if (!heap.isEmpty()) heap.deleteElement(index);

Try / catch

try {
    heap.deleteElement(index);
} catch (EmptyHeapException e) {
    // heap already empty; nothing to delete
}

Prevention

When it happens

Trigger: Calling deleteElement before any insert; calling delete after the heap was fully drained; a teardown routine that deletes unconditionally.

Common situations: Cleanup/teardown paths assuming occupancy; cancellation flows removing a job from an already-empty queue; tests with no setup.

Related errors


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