KeyNotFoundException in C#


The KeyNotFoundException is thrown when a key you are finding is not available in the Dictionary collection.

Let us see an example −

Example

 Live Demo

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);
      }
   }
}

The following is the output. The error KeyNotFoundException is visible since the key is not in the Dictionary −

Output

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

Updated on: 22-Jun-2020

428 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements