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.
var ages = new Dictionary<string, int> { ["Ada"] = 36 }; if (ages.TryGetValue("Bob", out int age)) { Console.WriteLine(age); }
Try it
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.
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
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] = valueadds or replaces. Only reading a missing key throws. Addthrows on duplicates.dict.Add(k, v)throwsArgumentExceptionif the key exists; useTryAddor the indexer.nullkeys. Anullkey throwsArgumentNullException, not this exception.- Prefer
TryGetValueoverContainsKeyplus indexer: it does one hash lookup instead of two. CollectionsMarshal.GetValueRefOrAddDefaultupdates a value in place with one lookup for hot paths.- Case sensitivity. The default string comparer is case-sensitive; pass
StringComparer.OrdinalIgnoreCaseto the constructor if keys differ by case only. - Lists use a different exception. A bad
List<T>index throwsArgumentOutOfRangeException. - Concurrent use. Reading while another thread writes may throw other errors; use
ConcurrentDictionary.