TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# KeyNotFoundException Fix

This C# exception article demonstrates the KeyNotFoundException.

KeyNotFoundException. A KeyNotFoundException was thrown.

This is likely caused by an invalid usage of the Dictionary collection. As always we want a quick way to fix the problem. We look at correct and incorrect examples.

Example. First, here we see some code that looks correct. But it has a severe flaw. This is the problem: you cannot look up a key that is not found in the Dictionary and try to assign your variable to its value.

Here: The KeyNotFoundException is thrown on the final line of try-block. The string "test" is not present in the collection.

TryCatch

C# program that throws KeyNotFoundException

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	try
	{
	    //
	    // Create new Dictionary with string key of "one"
	    //
	    Dictionary<string, string> test = new Dictionary<string, string>();
	    test.Add("one", "value");

	    //
	    // Try to access key of "two"
	    //
	    string value = test["two"];
	}
	catch (Exception ex)
	{
	    //
	    // An exception will be thrown.
	    //
	    Console.WriteLine(ex);
	}
    }
}

Output

System.Collections.Generic.KeyNotFoundException:
    The given key was not present in the dictionary.
at System.ThrowHelper.ThrowKeyNotFoundException()
...

Example 2. We can fix this exception by using the TryGetValue method on the Dictionary constructed type. Note that could use ContainsKey instead of TryGetValue, but the below code preserves the intention of the previous code.

ContainsKeyTryGetValue

C# program that does not throw

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	Dictionary<string, string> test = new Dictionary<string, string>();
	test.Add("one", "value");
	//
	// Use TryGetValue to avoid KeyNotFoundException.
	//
	string value;
	if (test.TryGetValue("two", out value))
	{
	    Console.WriteLine("Found");
	}
	else
	{
	    Console.WriteLine("Not found");
	}
    }
}

Output

Not found

You always have to use the if-statement when testing values in the Dictionary, because there is always a possibility that the key will not exist. The C# compiler cannot detect missing keys. They can only be detected at runtime.

Tester-DoerCompile-Time Error

Summary. We saw how to raise and catch the KeyNotFoundException during runtime. We then saw how to avoid causing the exception. We discussed alternatives, such as TryGetValue and ContainsKey, and looked at a program that does not have this problem.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf