TheAlgorithms/C-Sharp · error

Queue is empty.

Error message

Queue is empty.

What it means

PriorityQueue.Peek throws InvalidOperationException when the queue has no elements, since there is no front element to return. Called by GenerateShortestPath/target in AStar, it surfaces there when the code peeks a queue that should be non-empty.

Solutions

  1. Check Count > 0 before calling Peek (or use TryPeek if available).
  2. Verify the target node exists and is reachable before asking AStar for a path.
  3. Handle unreachable-target cases in calling code instead of letting the queue throw.

Example fix

// before
var node = queue.Peek();
// after
if (queue.Count == 0) return null;
var node = queue.Peek();
Defensive patterns

Strategy: try-catch

Validate before calling

if (queue.Count == 0) return null; // or handle empty case before peeking

Try / catch

try { var top = queue.Peek(); }
catch (InvalidOperationException) { return null; } // queue empty: target unreachable

Prevention

When it happens

Trigger: Peeking an empty queue directly, or reaching it via AStar when the search emptied the priority queue before the target was reconstructed (e.g. target unreachable and the path-generation step still calls Peek).

Common situations: Querying a path to an unreachable node in a disconnected graph; target node not present in the graph; caller forgetting Count/IsEmpty check before Peek.

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/36563ae061fb33da. Report an issue: GitHub.

Appendix: source

Thrown at Algorithms/Search/AStar/PriorityQueue.cs:128

        }

        if (Count > 0)
        {
            list[i] = root;
        }

        return target;
    }

    /// <summary>
    ///     Returns the next element in the queue without dequeuing.
    /// </summary>
    /// <returns>The next element of the queue.</returns>
    public T Peek()
    {
        if (Count == 0)
        {
            throw new InvalidOperationException("Queue is empty.");
        }

        return list[0];
    }

    /// <summary>
    ///     Clears the Queue.
    /// </summary>
    public void Clear() => list.Clear();

    /// <summary>
    ///     Returns the Internal Data.
    /// </summary>
    /// <returns>The internal data structure.</returns>
    public List<T> GetData() => list;
}

View on GitHub (pinned to 96e2905cab)