0

It seems that Microsoft Guidelines for creating custom exceptions state that there should be at least 3 public constructors: empty constructor, the one that takes a message and the one that takes a message and inner exception. My question is why do we need public constructors at all? If I m designing a framework that throws some custom exceptions (e.g. SomethingNotFoundException, etc.), then I would expect the framework users to catch my exceptions and handle them, but not throw them, since the APIs in the framework itself would throw them. So why not just have constructors as internal and only expose public properties that users need to handle these exceptions?

Yevgeniy P
  • 1,480
  • 1
  • 15
  • 23
  • Well, `public` in this sense does not really go well with your API-borders. I assume also MS wants to throw exceptions from different assemblies which assumes those exceptions to be `public`, even though no-one else should be able to throw them. E.g. a `DataException`, which can be thrown from many different assemblies. However you should not throw them yourself. – MakePeaceGreatAgain Feb 26 '20 at 12:03
  • I agree the exception classes themselves should be public, but why do they need public constructors if the users are not supposed to throw them? – Yevgeniy P Feb 27 '20 at 01:37
  • 1
    I think the reason for that advice is/was to allow for possibility that if one module performs something like a remote procedure call to another module running in a different process which throws an exception of type X, it might not be possible for the original module to access that exception object, but the remote-procedure-call mechanism may be able to construct a new exception of the same type in the original application and throw that. I'm not sure to what extent such situations end up being significant in practice. – supercat Feb 27 '20 at 03:37
  • I m wondering if in this case serialization will be used? I m not very familiar with C# serialization yet, so not sure if public constructors are needed to deserialize an object. But it seems that the constructors would be bypassed during deserialization. – Yevgeniy P Feb 28 '20 at 03:04

1 Answers1

0

Public constructor of user defined exception is required to for unit tests of client code which calls your method and have to handle exception might be thrown. But if a constructor requires argument of custom type either it still could be difficult properly instantiate.

At the same time Microsoft guideline for user defined exceptions contradicts YAGNI and KISS principles and suggests to write and leave unused code. If you have no plan to serialize your exception why to make it serializable? Additional code requires additional tests and so on which increases support cost or/and reduces reliability.

SerG
  • 1,251
  • 4
  • 18
  • 37