Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Why implement standard exception constructors?

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?
like image 545
Alexis Avatar asked May 31 '09 07:05

Alexis


2 Answers

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.

like image 172
Matthew Flaschen Avatar answered Sep 21 '22 12:09

Matthew Flaschen


You have gotten some good answers. I just want to add that providing these extra constructors does not necessarily require a lot of coding. Since they are already implemented in the base class, you can simply let that one do the work:

public class MyCustomException : Exception {     public MyCustomException() : base() { }     public MyCustomException(string message) : base(message) { }     public MyCustomException(string message, Exception innerException) : base(message, innerException) { }     // and so on... } 

So you will only need to implement code where the behaviour of your exception deviates from that of the base class.

like image 44
Fredrik Mörk Avatar answered Sep 18 '22 12:09

Fredrik Mörk