Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why .NET exceptions are mutable?

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...

like image 989
controlflow Avatar asked Jun 20 '10 18:06

controlflow


1 Answers

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.

like image 117
Stephen Cleary Avatar answered Oct 16 '22 00:10

Stephen Cleary