KeyNotFoundException은 찾고 있는 키가 Dictionarycollection에서 사용할 수 없는 경우 발생합니다.
예를 들어 보겠습니다 -
예시
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
try {
var dict = new Dictionary<string, string>() {
{"TV", "Electronics"},
{"Laptop", "Computers"},
};
Console.WriteLine(dict["Pen Drive"]);
}
catch (Exception e) {
Console.WriteLine(e);
}
}
} 다음은 출력입니다. 키가 사전에 없기 때문에 KeyNotFoundException 오류가 표시됩니다 -
출력
System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary. at System.Collections.Generic.Dictionary`2[TKey,TValue].get_Item (TKey key) [0x0001e] in <902ab9e386384bec9c07fa19aa938869>:0