title: Why doesn't .net provide us with the key when it raises a KeyNotFound Exception (and how can I get it?)
body: <p>When you try to access a key which isn't in a Dictionary (for example), here's the stack trace you get :</p>
  
  <pre><code>   at System.ThrowHelper.ThrowKeyNotFoundException()
       at System.Collections.Generic.Dictionary`2.get_Item(TKey key)   
         .... .... (my own code stack trace)
  </code></pre>
  
  <p>Like most people probably do, I log this errors when they occur, and try to figure out what happened.</p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>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?</p>
  
  <p>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.</p>
  
  <p>What do you think ?</p>
  
  <hr>
  
  <p>I'm aware of <a href="https://stackoverflow.com/questions/157911/in-a-net-exception-how-to-get-a-stacktrace-with-argument-values">this question</a>, 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.</p>
  
  <hr>
  
  <p>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 <em>before</em> (ie at the time when the key should have been inserted)</p>
  
  <p>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.</p>