Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Exceptions and Diagnostics

KeyNotFoundException

Reference for KeyNotFoundException in C#: why dictionary indexers throw, and how TryGetValue, ContainsKey, GetValueOrDefault and TryAdd avoid it.

KeyNotFoundException is thrown when you look up a key that is not present, most often with the indexer of a Dictionary<TKey,TValue>: dict["missing"]. Other keyed collections such as SortedDictionary, ReadOnlyDictionary and ImmutableDictionary behave the same way. LINQ's ToDictionary never throws it, but it does throw ArgumentException for duplicate keys.

When a missing key is a normal situation, do not use the indexer and catch the exception. Use TryGetValue, GetValueOrDefault or ContainsKey. Reserve the throwing indexer for cases where a missing key is truly a bug.

C#
var ages = new Dictionary<string, int> { ["Ada"] = 36 };
if (ages.TryGetValue("Bob", out int age)) { Console.WriteLine(age); }

Try it

C# The exception and the safe alternatives

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Counting words and updating safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public class KeyNotFoundException : SystemException
{
    public KeyNotFoundException();
    public KeyNotFoundException(string? message);
    public KeyNotFoundException(string? message, Exception? innerException);
}

bool TryGetValue(TKey key, out TValue value)   // Dictionary<TKey,TValue>
TValue? GetValueOrDefault<TKey,TValue>(this IReadOnlyDictionary<TKey,TValue> d, TKey key)
bool TryAdd(TKey key, TValue value)
Method Description
dict[key] Returns the value or throws KeyNotFoundException.
TryGetValue Returns true and sets value if found; otherwise false and default.
GetValueOrDefault Returns the value or default (or a supplied fallback).
ContainsKey Only tests for presence.
TryAdd Adds the pair and returns true, or returns false if the key already exists.

Usage notes

  • Message text. The runtime message names the key, for example "The given key 'banana' was not present in the dictionary." Avoid putting secrets into keys for this reason.
  • Assignment never throws. dict[key] = value adds or replaces. Only reading a missing key throws.
  • Add throws on duplicates. dict.Add(k, v) throws ArgumentException if the key exists; use TryAdd or the indexer.
  • null keys. A null key throws ArgumentNullException, not this exception.
  • Prefer TryGetValue over ContainsKey plus indexer: it does one hash lookup instead of two.
  • CollectionsMarshal.GetValueRefOrAddDefault updates a value in place with one lookup for hot paths.
  • Case sensitivity. The default string comparer is case-sensitive; pass StringComparer.OrdinalIgnoreCase to the constructor if keys differ by case only.
  • Lists use a different exception. A bad List<T> index throws ArgumentOutOfRangeException.
  • Concurrent use. Reading while another thread writes may throw other errors; use ConcurrentDictionary.