Ilya Chernomordik
Ilya Chernomordik

Reputation: 30205

Why does not .NET add parameter value to exception message, e.g. in int.Parse

Very often in .NET methods throw generic errors like e.g.

int.Parse("test")

throws an exception with this message:

Input string was not in a correct format.

Now it would save a lot of trouble for many people if it just had the parameter value to help debug things easier:

Input string "test" was not in a correct format.

This seems like a natural and easy thing to have, yet .NET does not do it in many places like e.g. parsing. Is there is any reason or conceptual problem with doing that or is it just a "missing feature"?

Upvotes: 4

Views: 245

Answers (1)

DiskJunky
DiskJunky

Reputation: 4971

I suspect that the reason is primarily for security reasons. Some concerns with displaying/rendering the text to be parsed in the message returned are (but not limited to)

  • The text to be parsed may be very long. This is would be problematic from a memory usage and display perspective not to mention developer's habits of logging exception messages (not unreasonably).
  • The text may contain characters that mess with the formatting (e.g., tab, LF, CR, etc.)
  • The text may contain sensitive data. On this point, it's worth nothing that most developers, at least starting out, generally log or display error messages at an exception level by default. Not including the text here means there's no unintended data leak to catch the unwary.
  • It's conceivable (though unlikely) that an exploit could be found whereby a malformed piece of text could have a nasty unintended side effect.

Additionally, the value being parsed is being supplied by the caller which leaves them the option of deciding if it's best to log the content or not - it's not int.Parse()'s place to return the value in the exception message.

All in all, displaying a concise message without the originally supplied value is a judicious decision on part of MS to save us from ourselves as well as follow security best practices.

Upvotes: 4

Related Questions