TheAlgorithms/C-Sharp · error · InvalidOperationException

Heap is empty

Error message

Heap is empty

What it means

MinMaxHeap.ExtractMax() throws InvalidOperationException("Heap is empty") when Count == 0. The library refuses to remove the maximum from an empty heap because there is no element to return. It is a guard against operating on uninitialized/emptied heap state.

Solutions

  1. Check heap.Count > 0 before calling ExtractMax()
  2. Wrap the call in try/catch for InvalidOperationException if draining until empty
  3. Restructure drain loops to use while (heap.Count > 0) { heap.ExtractMax(); }

Example fix

// before
var max = heap.ExtractMax();
// after
if (heap.Count == 0) return default; // or handle empty case
var max = heap.ExtractMax();
Defensive patterns

Strategy: validation

Validate before calling

if (heap.Count == 0) { /* handle empty: return default / skip */ } else { var max = heap.ExtractMax(); }

Try / catch

try { var max = heap.ExtractMax(); } catch (InvalidOperationException) { /* heap drained */ }

Prevention

When it happens

Trigger: Calling ExtractMax() on a MinMaxHeap with zero elements — e.g. calling it before any Insert, or calling it more times than items were inserted (including after prior ExtractMax/ExtractMin calls drained the heap).

Common situations: Looping 'while' over a heap to drain it without checking Count first; merging/priority-queue code that pops a max after a failed insert path; heap-sort implementations that call ExtractMax an off-by-one number of times.

Understand the failure class

Background: EmptyResultError / "no results found": when an API or scraper succeeds but returns zero rows — this error's family across 9 libraries.

Related errors


AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13). Data as JSON: /api/errors/584056837dbeb1db. Report an issue: GitHub.

Appendix: source

Thrown at DataStructures/Heap/MinMaxHeap.cs:61

    ///     Adds an element to the heap.
    /// </summary>
    /// <param name="item">The element to add to the heap.</param>
    public void Add(T item)
    {
        heap.Add(item);
        PushUp(Count - 1);
    }

    /// <summary>
    ///     Removes the maximum node from the heap and returns its value.
    /// </summary>
    /// <exception cref="InvalidOperationException">Thrown if heap is empty.</exception>
    /// <returns>Value of the removed maximum node.</returns>
    public T ExtractMax()
    {
        if (Count == 0)
        {
            throw new InvalidOperationException("Heap is empty");
        }

        var max = GetMax();
        RemoveNode(GetMaxNodeIndex());
        return max;
    }

    /// <summary>
    ///     Removes the minimum node from the heap and returns its value.
    /// </summary>
    /// <exception cref="InvalidOperationException">Thrown if heap is empty.</exception>
    /// <returns>Value of the removed minimum node.</returns>
    public T ExtractMin()
    {
        if (Count == 0)
        {
            throw new InvalidOperationException("Heap is empty");
        }

View on GitHub (pinned to 96e2905cab)