Best way to handle a KeyNotFoundException
I am using a dictionary to perform lookups for a program I am working on. I run a bunch of keys through the dictionary, and I expect some keys to not have a value. I catch the KeyNotFoundException
right where it occurs, and absorb it. All other exceptions will propagate to the top. Is this the best way to handle this? Or should I use a different lookup? The dictionary uses an int as its key, and a custom class as its value.
Use Dictionary.TryGetValue
instead:
Dictionary<int,string> dictionary = new Dictionary<int,string>();
int key = 0;
dictionary[key] = "Yes";
string value;
if (dictionary.TryGetValue(key, out value))
{
Console.WriteLine("Fetched value: {0}", value);
}
else
{
Console.WriteLine("No such key: {0}", key);
}
Try using: Dict.ContainsKey
Edit:
Performance wise i think Dictionary.TryGetValue
is better as some other suggested but i don't like to use Out when i don't have to so in my opinion ContainsKey is more readable but requires more lines of code if you need the value also.