KeyNotFoundException তখন ফেলা হয় যখন Dictionary-এ থাকা না থাকা কোনো কী (key) দিয়ে ভ্যালু এক্সেস করার চেষ্টা করা হয়।
উদাহরণ
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
try {
var dict = new Dictionary {
{ "TV", "Electronics" },
{ "Laptop", "Computers" }
};
// "Pen Drive" কী আছে না
Console.WriteLine(dict["Pen Drive"]);
} catch (Exception e) {
Console.WriteLine(e);
}
}
}
আউটপুট
System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
টিপস: এক্সেস করার আগে ContainsKey() বা TryGetValue() ব্যবহার করে কী আছে কিনা চেক করুন।