{"record":{"id":"68f818546b08bcb1","repo":"TheAlgorithms/C-Sharp","slug":"key-key-is-not-in-the-b-tree","errorCode":null,"errorMessage":"Key \"{key}\" is not in the B-Tree.","messagePattern":"Key \"(.+?)\" is not in the B-Tree\\.","errorType":"exception","errorClass":"KeyNotFoundException","httpStatus":null,"severity":"error","filePath":"DataStructures/BTree/BTree.cs","lineNumber":150,"sourceCode":"    {\n        foreach (var key in keys)\n        {\n            Add(key);\n        }\n    }\n\n    /// <summary>\n    ///     Remove a key from the tree.\n    /// </summary>\n    /// <param name=\"key\">Key value to remove.</param>\n    /// <exception cref=\"KeyNotFoundException\">\n    ///     Thrown when the key is not found in the tree.\n    /// </exception>\n    public void Remove(TKey key)\n    {\n        if (root is null)\n        {\n            throw new KeyNotFoundException($\"\"\"Key \"{key}\" is not in the B-Tree.\"\"\");\n        }\n\n        Remove(root, key);\n\n        if (root.KeyCount == 0)\n        {\n            root = root.IsLeaf ? null : root.Children[0];\n        }\n\n        Count--;\n    }\n\n    /// <summary>\n    ///     Check if given key is in the tree.\n    /// </summary>\n    /// <param name=\"key\">Key value to search for.</param>\n    /// <returns>Whether or not the key is in the tree.</returns>\n    public bool Contains(TKey key)","sourceCodeStart":132,"sourceCodeEnd":168,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/DataStructures/BTree/BTree.cs#L132-L168","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Guard with a Count/IsEmpty check (or root existence) before calling Remove.","Catch KeyNotFoundException when emptiness is an expected runtime state.","Restructure removal loops to stop when the tree is empty (e.g. while (btree.Count > 0)) instead of iterating a fixed number of times.","Verify the population path (Insert calls, initialization) actually ran before removal logic."],"exampleFix":"// before\nforeach (var key in keysToRemove)\n{\n    btree.Remove(key); // throws if tree already empty\n}\n\n// after\nforeach (var key in keysToRemove)\n{\n    if (btree.Count > 0)\n    {\n        btree.Remove(key);\n    }\n}","handlingStrategy":"try-catch","validationCode":"// C#\nif (btree is null || btree.Count == 0)\n{\n    // tree empty — skip removal\n}\nelse\n{\n    btree.Remove(key);\n}","typeGuard":"// C#\nstatic bool CanRemove<TK>(BTree<TK>? tree) => tree is not null && tree.Count > 0;","tryCatchPattern":"// C#\ntry\n{\n    btree.Remove(key);\n}\ncatch (KeyNotFoundException ex)\n{\n    // empty tree — log and continue\n}","preventionTips":["Check Count/IsEmpty before any Remove call.","Terminate drain loops on emptiness, not on a precomputed key count.","Re-verify initialization/population code paths before removal logic runs.","After Clear() or full drains, reset any cached references that still call Remove."],"tags":["keynotfound","b-tree","remove","empty-tree"],"backgroundTag":"record-not-found","analyzedSha":"96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c","analyzedAt":"2026-09-13T17:04:01.438Z","contentChangedAt":"2026-09-13T17:04:01.438Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}