KeyNotFoundException được đưa ra khi một khóa bạn đang tìm không có sẵn trong Bộ sưu tập từ điển.
Hãy để chúng tôi xem một ví dụ -
Ví dụ
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);
}
}
} Sau đây là kết quả đầu ra. Lỗi KeyNotFoundException hiển thị vì khóa không có trong theDictionary -
Đầu ra
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