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:
- Does a
KeyNotFoundExceptionstore/expose what key it tried to find? When I looked in the documentation, I did not see anything that implied this information was available. - 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!
A
KeyNotFoundExceptionis caused by trying to get the value out of a Dictionary with a given key when they key is not present. For example: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:You can look at the
StackTraceproperty of theyKeyNotFoundExceptionto determine exactly where the problem is happening. All exceptions have theStackTraceproperty, so you don’t need to care what type of exception it was in your global error handler. For example:Or, if you want to be able to tell what type of Exception it is: