KeyNotFoundException को तब फेंका जाता है जब आपके द्वारा खोजी जा रही कुंजी डिक्शनरी संग्रह में उपलब्ध नहीं होती है।
आइए एक उदाहरण देखें -
उदाहरण
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