Giới thiệu
KeyNotFoundException được ném ra khi cố gắng truy cập một khóa (key) không tồn tại trong Dictionary<TKey, TValue> thông qua indexer (ví dụ: dict["key"]).
Ví dụ gây ra ngoại lệ
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
try
{
var dict = new Dictionary()
{
{"TV", "Electronics"},
{"Laptop", "Computers"}
};
// Khóa "Pen Drive" không tồn tại
Console.WriteLine(dict["Pen Drive"]);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
Kết quả
System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary. at System.Collections.Generic.Dictionary`2.get_Item(TKey key) at Demo.Main()
Cách xử lý an toàn
1. Dùng ContainsKey()
if (dict.ContainsKey("Pen Drive"))
{
Console.WriteLine(dict["Pen Drive"]);
}
2. Dùng TryGetValue() (khuyên dùng)
if (dict.TryGetValue("Pen Drive", out string value))
{
Console.WriteLine(value);
}
else
{
Console.WriteLine("Không tìm thấy khóa.");
}
3. Dùng indexer với điều kiện null (C# 7.0+)
string value = dict.GetValueOrDefault("Pen Drive", "Mặc định");
Lưu ý
TryGetValue()hiệu quả hơn vì chỉ tra cứu một lần.- Tránh dùng try-catch cho luồng điều khiển bình thường (performance).
KeyNotFoundExceptionkế thừa từSystemException.