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