When you try to access a key which isn't in a Dictionary (for example), here's the stack trace you get :
at System.ThrowHelper.ThrowKeyNotFoundException()
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
.... .... (my own code stack trace)
Like most people probably do, I log this errors when they occur, and try to figure out what happened.
The two key informations I want are where did this occur (the stacktrace is very helpful for that), and the key which caused the exception, which doesn't appear anywhere.
Either I didn't look properly (the KeyNotFoundException class contains a "Data" member, which is always empty, and the "Message" field" doesn't contain the key value), or it wasn't included in the framework at all.
I can't imagine nobody in the .net BCL team thought this would be an useful feature to have. I'm curious to know why they didn't include it. Are there some good reasons not to?
How do you deal with those exceptions ? The only alternative I can think of is to use a custom extension method on Dictionary which would wrap the call, catch the exception, and rethrow it with additional information regarding the key, but that wouldn't help for code I don't own, and it feel broken to change such a "base" functionality.
What do you think ?
I'm aware of this question, regarding the general fact that one cannot access the arguments of the method which raised an exception. My question is specifically related to the KeyNotFoundException.
Edit : I'm aware of the TryGetValue pattern, I do that all the time when I expect that my collection may not contain the key. But when it should contain it, I don't test, because I prefer my program to fail with an exception so that I know something unexpected happened before (ie at the time when the key should have been inserted)
I could wrap a try/catch/log error/rethrow around all my dictionary access, but this would lead to difficult-to-read code, cluterred with all my exception handling/logging stuff.