user208662 user208662 - 10 days ago 8
C# Question

KeyNotFoundException info

I have an C# Silverlight application that is randomly throwing a "

KeyNotFoundException
". I have no idea what key cannot be found. This has lead me to two questions:


  1. Does a
    KeyNotFoundException
    store/expose what key it tried to find? When I looked in the documentation, I did not see anything that implied this information was available.

  2. I am catching/logging this exception in a general Application.UnhandledException event handler. My question is, if I catch the event here, can I convert the ExceptionObject to a KeyNotFoundException and still get the key information if its exposed as asked in #1?



Thank you so much for your help!

Answer

A KeyNotFoundException is caused by trying to get the value out of a Dictionary with a given key when they key is not present. For example:

var dictionary = new Dictionary<string, string>();
var val = dictionary["mykey"];

You can look at all of the places where a dictionary is being used and determine yourself. A general best practice for that is if you are looking for a value in a dictionary that might not be present would be to use TryGetValue. Catching the exception every time is a more expensive operation and is unnecessary:

string val;
if(dictionary.TryGetValue("mykey", out val))
{
     //The key was found. The value is in val.
}
else
{
    //The key was not present.
}

You can look at the StackTrace property of they KeyNotFoundException to determine exactly where the problem is happening. All exceptions have the StackTrace property, so you don't need to care what type of exception it was in your global error handler. For example:

private void Application_UnhandledException(object sender, 
        ApplicationUnhandledExceptionEventArgs e)
    {
         var stackTrace = e.ExceptionObject.StackTrace;
         //Log the stackTrace somewhere.
    }

Or, if you want to be able to tell what type of Exception it is:

private void Application_UnhandledException(object sender, 
        ApplicationUnhandledExceptionEventArgs e)
    {
         if (e.ExceptionObject is KeyNotFoundException)
         {
             //This was a KeyNotFoundException
         }
    }