TheAlgorithms/C-Sharp · error · InvalidOperationException

Heap is empty!

Error message

Heap is empty!

What it means

BinaryHeap.Pop() throws InvalidOperationException when the heap has zero elements, because there is no root to return. It is a deliberate guard so callers never receive a default T from an empty collection.

Solutions

  1. Check Count > 0 (or TryPop-style pattern) before calling Pop().
  2. Wrap Pop() in try-catch on InvalidOperationException if emptiness is expected.
  3. Fix loop logic so Pop is only called once per Push.

Example fix

// before
var top = heap.Pop();
// after
if (heap.Count > 0)
{
    var top = heap.Pop();
}
Defensive patterns

Strategy: validation

Validate before calling

if (heap.Count > 0) { var top = heap.Pop(); }

Try / catch

try { var top = heap.Pop(); } catch (InvalidOperationException) { /* handle empty */ }

Prevention

When it happens

Trigger: Calling Pop() on a new BinaryHeap<T> or after popping all previously pushed elements (Count == 0).

Common situations: Draining a priority queue in a loop without checking Count, popping before any Push, or a producer/consumer race where the queue was consumed by another path.

Understand the failure class

Background: UnsupportedOperationException and "is not supported" errors: when a library deliberately refuses a call — this error's family across 30 libraries.

Related errors


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

Appendix: source

Thrown at DataStructures/Heap/BinaryHeap.cs:81

        data.Add(element);
        HeapifyUp(data.Count - 1);
    }

    /// <summary>
    ///     Remove the top/root of the binary heap (ie: the largest/smallest element).
    /// </summary>
    /// <remarks>
    ///     Removing from the heap is done by swapping the top/root with the last element in
    ///     the backing list, removing the last element, and pushing the new root down
    ///     until the heap property is restored.
    /// </remarks>
    /// <returns>The top/root of the heap.</returns>
    /// <exception cref="InvalidOperationException">Thrown if heap is empty.</exception>
    public T Pop()
    {
        if (Count == 0)
        {
            throw new InvalidOperationException("Heap is empty!");
        }

        var elem = data[0];
        data[0] = data[^1];
        data.RemoveAt(data.Count - 1);
        HeapifyDown(0);

        return elem;
    }

    /// <summary>
    ///     Return the top/root of the heap without removing it.
    /// </summary>
    /// <returns>The top/root of the heap.</returns>
    /// <exception cref="InvalidOperationException">Thrown if heap is empty.</exception>
    public T Peek()
    {
        if (Count == 0)

View on GitHub (pinned to 96e2905cab)