C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Here: The KeyNotFoundException is thrown on the final line of the try-block. The string "test" is not present in the collection.
TryCatchC# 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()
...
Important: We use if-statement when testing values in the Dictionary, because there is always a possibility that the key will not exist.
IfRuntime: The C# compiler cannot detect missing keys. They can only be detected at runtime.
DictionaryC# 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