C# – Why implement standard exception constructors

ccoding-styleexception

From MSDN, code analysis warning CA1032:

Exception types must implement the following constructors: 
  • public NewException()
  • public NewException(string)
  • public NewException(string, Exception)
  • protected or private NewException(SerializationInfo, StreamingContext)

I understand the purpose behind the serialization constructor, but is the rationale behind "requiring" the others? Why shouldn't I just define whatever constructors make sense for usage of my exception? What if I never want to throw MyException without passing in a message- why should I define a parameterless constructor? What if I want MyException to have an int property and I only want constructors that initialize that property?

Best Answer

This is a warning, not a requirement. It's basically principle of least surprise. Providing all 4 makes it easier for people used to "regular" C# exceptions to use yours. If you have a good reason to ignore the guideline, do so. But it will break certain usage scenarios, and make your class a little less intuitive.