TheAlgorithms/C-Sharp · error · InvalidOperationException
Heap is empty!
Error message
Heap is empty!
What it means
This InvalidOperationException is the empty-heap guard at the start of FibonacciHeap.Pop (FibonacciHeap.cs:159). Pop removes the minimum node, which requires MinItem to reference a real root-list node; when MinItem is null the heap holds no elements and there is nothing to remove. It fires when Pop is called on a heap with Count == 0, or after all elements have already been popped.
Solutions
- Check heap.Count > 0 or MinItem != null before Pop().
- Catch InvalidOperationException when empty is a valid state.
- Guard extraction loops to stop when the heap is empty.
Example fix
// before
var min = heap.Pop();
// after
if (heap.Count > 0)
{
var min = heap.Pop();
} Defensive patterns
Strategy: validation
Validate before calling
if (heap.Count > 0) { var min = heap.Pop(); } Try / catch
try { var min = heap.Pop(); } catch (InvalidOperationException) { /* heap empty */ } Prevention
- Guard extraction loops with Count > 0
- Track heap size alongside graph algorithm state
- Do not pop after full drain
When it happens
Trigger: Calling Pop() on a new FibonacciHeap<T>, after popping all nodes, or on a heap made empty by Union with an empty other heap.
Common situations: Dijkstra/Prim loops that pop without checking Count or MinItem, or draining the heap fully and popping once more.
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/23a880019e31916e.
Report an issue: GitHub.
Appendix: source
Thrown at DataStructures/Heap/FibonacciHeap/FibonacciHeap.cs:159
/// or another of the items in the root list is a candidate to become the new
/// MinItem.
/// </item>
/// <item>
/// Remove the MinItem from the root list and appoint a new MinItem temporarily.
/// </item>
/// <item>
/// <see cref="Consolidate" /> what's left
/// of the heap.
/// </item>
/// </list>
/// </remarks>
/// <returns>The minimum item from the heap.</returns>
public T Pop()
{
FHeapNode<T>? z = null;
if (MinItem == null)
{
throw new InvalidOperationException("Heap is empty!");
}
z = MinItem;
// Since z is leaving the heap, add its children to the root list
if (z.Child != null)
{
foreach (var x in SiblingIterator(z.Child))
{
x.Parent = null;
}
// This effectively adds each child x to the root list
z.ConcatenateRight(z.Child);
}
if (Count == 1)
{View on GitHub (pinned to 96e2905cab)