I'm sure I've seen this in various exception messages in the framework. I checked the following pages from the MSDN library but could not find much guidance for the message contents:
Exception Throwing
Error Message Design
Exception.Message Property
The only part in the first page that could explain it is this text:
Do not disclose security-sensitive information in exception messages without demanding appropriate permissions.
It's the the ArgumentException thrown by Dictionary<TKey, TValue>.Add method that reminded me of this issue. It looks like this:
System.ArgumentException : An item with the same key has already been added.
Why does it not look something like this?
System.ArgumentException : An item with the same key(123) has already been added.
This assumes 123 is the TKey value, basically any format with the TKey value is what I would thing would be useful to track down an error while debugging.
Is there a known reason why this is not included?
Would it be considered bad practice to re-thrown the argument exception with the key in the message? I had considered making my own exception subclass but I think this is a case where using a built in exception class seems like a better option.
Exception messages depend on the transaction being carried out and are meant to inform you of an important or critical event (for example, start date lies in the past, safety stock has been exceeded). By means of the exception messages, you can easily sort out any materials that you need to reprocess manually.
From Best Practices for Exceptions† on MSDN in the section "Creating and raising exceptions": Use grammatically correct error messages, including ending punctuation. Each sentence in a description string of an exception should end in a period.
As a rule of thumb, exceptional situations in frameworks want to avoid creating new exceptional situations. To format the message like this:
System.ArgumentException : An item with the same key(123) has already been added.
One would have to assume there is a valid implementation of toString
on the key parameter. But what if it is null
? Or if it is a custom key that throws a new exception in its toString
? Or even some idiot implemented a toString
method that throws a random exception 1 out of 10 times? What if the internal exception was caused by an out of memory situation and the conversion would just trigger it again? It would give more unpredictable results than just reporting what it is sure to be able to report.
It looks like a security precaution. The program could be working with security-sensitive data, which it takes care not to write into log messages or reveal through the UI. But, oops, there is a problem and an unhandled exception goes off, where some default handler displays or logs pieces of that sensitive information because it was included in the exception text.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With