TheAlgorithms/C-Sharp · error · KeyNotFoundException

Key " " is not in the B-Tree.

Error message

Key "{key}" is not in the B-Tree.

What it means

This KeyNotFoundException is thrown by BTree.Remove(TKey) when the tree's root is null, i.e. the tree contains no keys, so nothing can be removed. Like the AVL tree, the library fails fast on removing an absent key rather than silently ignoring it. Note the exception fires before searching when the tree is empty; a key absent from a non-empty tree is handled by the internal search without throwing here.

Solutions

  1. Guard with a Count/IsEmpty check (or root existence) before calling Remove.
  2. Catch KeyNotFoundException when emptiness is an expected runtime state.
  3. Restructure removal loops to stop when the tree is empty (e.g. while (btree.Count > 0)) instead of iterating a fixed number of times.
  4. Verify the population path (Insert calls, initialization) actually ran before removal logic.

Example fix

// before
foreach (var key in keysToRemove)
{
    btree.Remove(key); // throws if tree already empty
}

// after
foreach (var key in keysToRemove)
{
    if (btree.Count > 0)
    {
        btree.Remove(key);
    }
}
Defensive patterns

Strategy: try-catch

Validate before calling

// C#
if (btree is null || btree.Count == 0)
{
    // tree empty — skip removal
}
else
{
    btree.Remove(key);
}

Type guard

// C#
static bool CanRemove<TK>(BTree<TK>? tree) => tree is not null && tree.Count > 0;

Try / catch

// C#
try
{
    btree.Remove(key);
}
catch (KeyNotFoundException ex)
{
    // empty tree — log and continue
}

Prevention

When it happens

Trigger: Calling btree.Remove(key) on a tree constructed but never populated, or after all keys were removed (the root becomes null/empty after removal shrinks the tree). Also reachable in loops that remove every key and then attempt one more removal.

Common situations: Draining a B-tree in a loop that overshoots by one iteration; retrying removal of an item after the tree was cleared; deserialization that produced an empty tree while code assumed seeded data; unit-test teardown ordering issues.

Understand the failure class

Background: Record Not Found Errors: "not found", RecordNotFound, and "was not found" — what they mean and how to fix them — this error's family across 28 libraries.

Related errors


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

Appendix: source

Thrown at DataStructures/BTree/BTree.cs:150

    {
        foreach (var key in keys)
        {
            Add(key);
        }
    }

    /// <summary>
    ///     Remove a key from the tree.
    /// </summary>
    /// <param name="key">Key value to remove.</param>
    /// <exception cref="KeyNotFoundException">
    ///     Thrown when the key is not found in the tree.
    /// </exception>
    public void Remove(TKey key)
    {
        if (root is null)
        {
            throw new KeyNotFoundException($"""Key "{key}" is not in the B-Tree.""");
        }

        Remove(root, key);

        if (root.KeyCount == 0)
        {
            root = root.IsLeaf ? null : root.Children[0];
        }

        Count--;
    }

    /// <summary>
    ///     Check if given key is in the tree.
    /// </summary>
    /// <param name="key">Key value to search for.</param>
    /// <returns>Whether or not the key is in the tree.</returns>
    public bool Contains(TKey key)

View on GitHub (pinned to 96e2905cab)