Using a Dictionary (Hashtable) - Page 3
       by kirupa  |  13 October 2006

In the previous page you learned the basic syntax for using a dictionary. In this page, I will explain how to avoid some roadblocks you may encounter during their use.

Error Handling - Missing/Wrong Keys
You may run into situations where the key you enter cannot be found by the dictionary. Unlike similar data structures where accessing data that doesn't exist results in a silent failure, you have to be careful of ensuring that the key you pass actually exists in your Dictionary object. If you pass in a value that does not exist, a KeyNotFoundException will be thrown:

In any application, the above error will crash the program. Therefore, it is best to recognize these errors and prevent them from causing damage. There are two ways you can do that:

  1. Checking if the key exists in the Dictionary prior to accessing the value.

  2. Using a try/catch block to catch the exception.

Let me explain the above two methods in greater detail.

Checking if Value Exists
To check if a value exists, you can use the Dictionary's containsKey method to return a true if the key exists or a false if the key does not exist:

//Using containsKey()
if (coffeeStat.ContainsKey("Kirupa")) {
Console.WriteLine("Value is: " + coffeeStat["Kirupa"]);
}

In the above example, if our coffeeStat dictionary object contains the key "Kirupa", the value will be displayed in the console.

Catching the Exception
In the above approach, you check whether a key exists before performing any operation on the dictionary involving the key. Another approach is to pass the key to your dictionary object and deal with the consequences later. That is where the try/catch statement comes in handy:

try
{
Console.WriteLine("Value is: " + coffeeStat["Kirupa"]);
}
catch (KeyNotFoundException e)
{
Console.WriteLine(e.Message);
}

In the above piece of code, you always pass "Kirupa" into the coffeeStat dictionary, and only if there is an error (a KeyNotFoundException), will the catch statement become active and execute any code contained within it.

Which Error Handling Method is Better?
Regardless of which approach you employ to check whether a key exists in a dictionary, you will ensure that your application does not crash. There are some performance implications with catching exceptions over containsKey, but we will not worry about that in this tutorial. Generally, catching exceptions is a bit slower than using containsKey.

Onwards to the next page!

1 | 2 | 3 | 4 | 5




SUPPORTERS:

kirupa.com's fast and reliable hosting provided by Media Temple.