Home
VB.NET
KeyNotFoundException (Dictionary)
This page was last reviewed on Nov 30, 2023.
Dot Net Perls
KeyNotFoundException. When using a Dictionary, we often access many different keys—and sometimes a key may not exist. In this case, a KeyNotFoundException may be thrown.
Dictionary
This exception means we tried to access a key that does not exist, in a way that does not prevent exceptions. To fix this problem in VB.NET, we can use a function like TryGetValue.
Dictionary TryGetValue
Exception
Example. Here we place a Dictionary key access inside a Try block, and then in the Catch block, we print the exception. This helps us understand more about the error.
Part 1 We create a Dictionary with String keys, and String values. We add just 1 key, the string "one".
Part 2 We access a key that does not exist, and this causes an exception. The Try block stops executing, and we reach the Catch block.
Part 3 We print the Exception (a KeyNotFoundException) to the console with Console.WriteLine.
Module Module1 Sub Main() Try ' Part 1: create a Dictionary and add 1 key. Dim test = New Dictionary(Of String, String)() test.Add("one", "value") ' Part 2: access a key that does not exist. Dim value = test("two") Catch ex as Exception ' Part 3: print the exception. Console.WriteLine(ex) End Try End Sub End Module
System.Collections.Generic.KeyNotFoundException: The given key 'two' was not present in the dictionary. at System.Collections.Generic.Dictionary`2.get_Item(TKey key) at ...
Example 2. How can we fix a KeyNotFoundException? We can use TryGetValue instead of the indexer to access a key. Then we place an If-Else around the TryGetValue call.
If
Module Module1 Sub Main() Dim test = New Dictionary(Of String, String)() test.Add("one", "value") ' Use TryGetValue for exception-free code. Dim value As String = Nothing If test.TryGetValue("two", value) Console.WriteLine("Found") Else Console.WriteLine("Not found") End If End Sub End Module
Not found
Summary. Using a function like TryGetValue (or GetValueOrDefault) is the best way to avoid the KeyNotFoundException. Usually an If-Else block must be placed around the new function call.
Dictionary GetValueOrDefault
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 30, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.