Search This Blog

Monday, June 15, 2015

KeyNotFoundException Collection C# Example

Collections > Generic > KeyNotFoundException 

This is thrown when try to retrieve an element from a collection using a key that does not exist in that collection.

Example

   Dictionary<string, string> dict = new Dictionary<string, string>();
   dict.Add("key1","value1");
   try
   {
       string val = dict["key2"];
   }
   catch (KeyNotFoundException)
   {
       throw new KeyNotFoundException("KeyNotFoundException!");

   }