kunal-kushwaha/DSA-Bootcamp-Java · error · Exception

Removing from an empty heap!

Error message

Removing from an empty heap!

What it means

Heap.remove() throws a checked Exception when the underlying list is empty, since there is no root element to extract. It is the heap's extract-min/max operation used by heapSort and other consumers, so underflow propagates into sorting/queue logic.

Source

Thrown at lectures/24-heaps/code/heaps-1/Heap.java:46

  public void insert(T value) {
    list.add(value);
    upheap(list.size() - 1);
  }
  private void upheap(int index) {
    if(index == 0) {
      return;
    }
    int p = parent(index);
    if(list.get(index).compareTo(list.get(p)) < 0) {
      swap(index, p);
      upheap(p);
    }
  }

  public T remove() throws Exception {
    if (list.isEmpty()) {
      throw new Exception("Removing from an empty heap!");
    }

    T temp = list.get(0);

    T last = list.remove(list.size() - 1);
    if (!list.isEmpty()) {
      list.set(0, last);
      downheap(0);
    }
    
    return temp;
  }
  private void downheap(int index) {
    int min = index;
    int left = left(index);
    int right = right(index);

    if(left < list.size() && list.get(min).compareTo(list.get(left)) > 0) {

View on GitHub (pinned to 6bc4d8bf8a)

Solutions

  1. Check heap size (isEmpty()) before each remove().
  2. Catch Exception around remove() and stop consuming when empty.
  3. Bound loops by heap size rather than a fixed count.

Example fix

// before
T min = heap.remove();
// after
if (!heap.isEmpty()) {
    T min = heap.remove();
}
Defensive patterns

Strategy: validation

Validate before calling

if (!heap.isEmpty()) {
    T min = heap.remove();
}

Try / catch

try {
    T min = heap.remove();
} catch (Exception e) {
    // heap exhausted — stop consuming
}

Prevention

When it happens

Trigger: Calling remove() on a Heap whose list is empty: removing more elements than were inserted, running heapSort on an empty or over-drained heap, or a second remove after the heap was exhausted.

Common situations: Priority-queue consumers polling until 'done' without checking size; heapSort loops with an off-by-one iteration; K-way merge code removing once per input when fewer inputs exist; reusing a heap after it was fully drained.

Related errors


AI-assisted analysis of kunal-kushwaha/DSA-Bootcamp-Java@6bc4d8bf8a (2026-08-31). Data as JSON: /api/errors/752726fde9ebc1c1. Report an issue: GitHub.