views:

76

answers:

1

I'm wondering why .NET exceptions classes from Base Class Library has some mutable members by default

  • Why I can change the Source, HelpLink and values from Data, but can't change anything else like the Message?
  • Why throwing the exception rewrites the StackTrace making it mutable too? Is appending the stack trace information to existing trace would be better design (but still mutable)?
  • What possible improvements in .NET exceptions design may be?

I'm interesting just in design choices...

+6  A: 

The StackTrace makes sense to me, at least. The idea is that an Exception (as an object) may be passed around, returned from methods, etc. The StackTrace is only important as an exception is thrown and caught. In a sense, StackTrace is really more of a property of the throwing of the exception, not the Exception object itself.

Regarding the mutability of the other properties, I assume it is just because it's easier to construct an instance by assigning to properties rather than forcing them all into the constructor. Remember that at the time Exception was designed, C# did not have optional parameters.

You could consider a re-design where Exception and derived classes are immutable, but this would require an exception factory or builder class. It would just make deriving from Exception that much more complex.

Stephen Cleary
ok, if the problem is the passing a lot of data into exception, why the `Message` property is readonly?
ControlFlow
nice thoughts about `StackTrace`...
ControlFlow
`Message` is the one non-optional piece of information, so it makes sense to put it in the constructor.
Stephen Cleary