TheAlgorithms/C-Sharp · error · InvalidOperationException

The heap is empty

Error message

The heap is empty

What it means

This InvalidOperationException is the empty-heap guard in FibonacciHeap.Peek (FibonacciHeap.cs:209). Peek returns MinItem.Key without modifying the heap; when MinItem is null the heap has no elements, so no minimum key exists to return. It fires whenever Peek is called on an empty (Count == 0) FibonacciHeap.

Solutions

  1. Check heap.Count > 0 before Peek().
  2. Catch InvalidOperationException when emptiness is expected.
  3. Insert at least one element before querying the minimum.

Example fix

// before
var min = heap.Peek();
// after
var min = heap.Count > 0 ? heap.Peek() : throw new EmptyHeapException();
Defensive patterns

Strategy: validation

Validate before calling

if (heap.Count == 0) return; // or default
var min = heap.Peek();

Try / catch

try { var min = heap.Peek(); } catch (InvalidOperationException) { /* empty heap path */ }

Prevention

When it happens

Trigger: Calling Peek() on an empty FibonacciHeap<T> (no Push yet, or fully drained).

Common situations: Reading the minimum before inserting elements, or peeking after a drain loop in graph algorithms.

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/5d88b61a3c192a09. Report an issue: GitHub.

Appendix: source

Thrown at DataStructures/Heap/FibonacciHeap/FibonacciHeap.cs:209

        Consolidate();

        Count -= 1;

        return z.Key;
    }

    /// <summary>
    ///     A method to see what's on top of the heap without changing its structure.
    /// </summary>
    /// <returns>
    ///     Returns the top element without popping it from the structure of
    ///     the heap.
    /// </returns>
    public T Peek()
    {
        if (MinItem == null)
        {
            throw new InvalidOperationException("The heap is empty");
        }

        return MinItem.Key;
    }

    /// <summary>
    ///     Reduce the key of x to be k.
    /// </summary>
    /// <remarks>
    ///     k must be less than x.Key, increasing the key of an item is not supported.
    /// </remarks>
    /// <param name="x">The item you want to reduce in value.</param>
    /// <param name="k">The new value for the item.</param>
    public void DecreaseKey(FHeapNode<T> x, T k)
    {
        if (MinItem == null)
        {
            throw new ArgumentException($"{nameof(x)} is not from the heap");

View on GitHub (pinned to 96e2905cab)