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.
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.
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 ModuleSystem.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.
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 ModuleNot 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.