none
Why does KeyNotFoundException not tell you what key? RRS feed

  • General discussion

  • Hi,

         This is really a complaint, but if there is a good reason, I would like to know...

    When C#.net throws a KeyNotFoundException, it doesn't tell you the value of the key which was not found. Why is that? It would be easy to write the exception code to include key.ToString() and, for me at least, it would frequently simplify my debugging.

        I find similar things for many exceptions where they seem to supply minimal info about the context of what when wrong. When I throw exceptions I generally try to add as much context as possible.

    Thanks,

    Ethan

      


    Ethan Strauss

    Wednesday, November 20, 2019 6:00 PM

All replies

  • While I agree that it would have been nice to include the key there are issues if it had. The first issue is that keys aren't necessarily strings and converting an arbitrary type to a string may not behave correctly. For example if I'm using a dictionary of objects then simply converting to string wouldn't be beneficial. If you really want this kind of functionality then create your own exception that does expose the key. This is what we do in our more complex code bases.

    The second issue is that the key may not be available. This would happen if the error occurred because of a COM failure. In that case COM wouldn't pass back the key and therefore it wouldn't be available. So, it could be an optional parameter to the exception but couldn't be required.

    As for the debugging portion you should be able to figure out where it went wrong via the callstack itself. If you're running in the debugger then you should be able to easily get the key information. If you're not running in the debugger then logging would be the workaround.

    However there is an alternative if you are the one throwing the exception. The Data property contains data about the exception. You could, if you are throwing or handling the exception, add the key to the Data property for higher level code to deal with. We use this approach for adding additional data to higher level callers.

    So, in summary, no particularly good reason it wasn't supported but it is too late to add it now.


    Michael Taylor http://www.michaeltaylorp3.net

    Wednesday, November 20, 2019 7:25 PM
    Moderator