Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 827
Dan McClain Avatar asked Mar 03 '09 14:03

Dan McClain


People also ask

How do you handle if the key is not present in Dictionary C#?

The Dictionary throws a KeyNotFound exception in the event that the dictionary does not contain your key. As suggested, ContainsKey is the appropriate precaution. TryGetValue is also effective. This allows the dictionary to store a value of null more effectively.

What is key not found exception?

A KeyNotFoundException is thrown when an operation attempts to retrieve an element from a collection using a key that does not exist in that collection. KeyNotFoundException uses the HRESULT COR_E_KEYNOTFOUND, which has the value 0x80131577.

How do you solve the given key was not present in the dictionary?

"The given key was not present in the dictionary." A better way would be: "The given key '" + key.

How do you check if a string is in a dictionary C#?

Syntax: public bool ContainsKey (TKey key); Here, the key is the Key which is to be located in the Dictionary. Return Value: This method will return true if the Dictionary contains an element with the specified key otherwise, it returns false.


2 Answers

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); } 
like image 83
Jon Skeet Avatar answered Oct 15 '22 17:10

Jon Skeet


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.

like image 38
Peter Avatar answered Oct 15 '22 17:10

Peter