C# 中的 KeyNotFoundException

csharpprogrammingserver side programming更新于 2025/8/11 22:07:17

当您查找的键在 Dictionary 集合中不存在时,会抛出 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);
      }
   }
}

以下是输出。由于键不在 Dictionary 中,因此错误 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

相关文章