TheAlgorithms/C-Sharp · error · InvalidOperationException

The stack contains no items.

Error message

The stack contains no items.

What it means

QueueBasedStack.Pop throws InvalidOperationException when the stack is empty, since there is no top item to remove and return. The guard `if (IsEmpty())` at the top of Pop ensures the caller never dequeues from the backing queue without at least one element present.

Solutions

  1. Check IsEmpty() (or Count > 0) before calling Pop
  2. Wrap Pop in try/catch for InvalidOperationException when empty-pop is an expected condition
  3. Refactor to use TryPop-style logic: if (stack.IsEmpty()) return default/early-exit instead of popping

Example fix

// before
var item = stack.Pop();
// after
if (stack.IsEmpty())
{
    throw new InvalidOperationException("Cannot pop from an empty stack."); // or return default
}
var item = stack.Pop();
Defensive patterns

Strategy: validation

Validate before calling

if (stack == null) throw new ArgumentNullException(nameof(stack));
if (stack.IsEmpty()) { /* handle empty: return default / skip / throw custom */ }

Try / catch

try { var item = stack.Pop(); }
catch (InvalidOperationException) { /* stack was empty — take fallback path */ }

Prevention

When it happens

Trigger: Calling Pop() on a new QueueBasedStack<T>, or after popping/peeking has consumed all pushed items (Push(a); Pop(); Pop() on a one-element stack).

Common situations: Looping over a collection pushing items but miscounting iterations so one extra Pop happens; popping from a stack shared across methods where one consumer already drained it; forgetting to check Count/IsEmpty before pop in generic 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/a585402207a0fe12. Report an issue: GitHub.

Appendix: source

Thrown at DataStructures/Stack/QueueBasedStack.cs:31

    public bool IsEmpty() => queue.Count == 0;

    /// <summary>
    ///     Adds an item on top of the stack.
    /// </summary>
    /// <param name="item">Item to be added on top of stack.</param>
    public void Push(T item) => queue.Enqueue(item);

    /// <summary>
    ///     Removes an item from  top of the stack and returns it.
    ///  </summary>
    /// <returns>item on top of stack.</returns>
    /// <exception cref="InvalidOperationException">Throw if stack is empty.</exception>
    public T Pop()
    {
        if (IsEmpty())
        {
            throw new InvalidOperationException("The stack contains no items.");
        }

        for (int i = 0; i < queue.Count - 1; i++)
        {
            queue.Enqueue(queue.Dequeue());
        }

        return queue.Dequeue();
    }

    /// <summary>
    ///     return an item from the top of the stack without removing it.
    /// </summary>
    /// <returns>item on top of the stack.</returns>
    /// <exception cref="InvalidOperationException">Throw if stack is empty.</exception>
    public T Peek()
    {
        if (IsEmpty())

View on GitHub (pinned to 96e2905cab)