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
.
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.
Dictionary
with String
keys, and String
values. We add just 1 key, the string
"one".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 ...
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
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.