Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

KeyNotFoundException — a missing collection key

System.Collections.Generic.KeyNotFoundException signals an attempt to retrieve an element using a key that does not exist. Learn how Dictionary<TKey,TValue> indexer reads differ from writes and when to use TryGetValue for an expected missing key.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

try { var value = dictionary[key]; }
catch (System.Collections.Generic.KeyNotFoundException) { /* Handle the missing key. */ }

System.Collections.Generic.KeyNotFoundException is an exception type that signals an attempt to retrieve a collection element using a key that the collection does not contain. The type is available in .NET 10; using it does not require preview language features.

For Dictionary<TKey,TValue>, reading dictionary[key] throws this exception if the key does not exist. Writing dictionary[key] = value behaves differently: it adds a missing key or replaces the value of an existing key. A missing key therefore does not mean that every indexer operation throws.

When a missing key is expected, use TryGetValue(key, out value) instead of using try/catch for ordinary control flow. The method returns false and assigns default(TValue) to the output parameter if the key is absent. For int, this is 0; check the Boolean result because 0 can also be a legitimately stored value.

The example deliberately triggers and catches KeyNotFoundException, then demonstrates TryGetValue and adding the missing key through assignment. The catch block prints fixed text rather than the system exception message, so the expected output does not depend on the runtime's message language.

Examples

using System;
using System.Collections.Generic;

internal static class Program
{
    private static void Main()
    {
        var scores = new Dictionary<string, int>
        {
            ["Ada"] = 10
        };

        try
        {
            Console.WriteLine(scores["Lin"]);
        }
        catch (KeyNotFoundException)
        {
            Console.WriteLine("Missing key: Lin");
        }

        if (!scores.TryGetValue("Lin", out int score))
        {
            Console.WriteLine($"Not found; out value: {score}");
        }

        scores["Lin"] = 20;
        Console.WriteLine(scores["Lin"]);
    }
}

Result

Missing key: Lin
Not found; out value: 0
20

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources