How to handle incorrect values in a constructor?

后端 未结 11 1363
野性不改
野性不改 2020-12-17 08:44

Please note that this is asking a question about constructors, not about classes which handle time.

Suppose I have a class like this:



        
11条回答
  •  甜味超标
    2020-12-17 09:17

    Just to elaborate a bit on the answers given by onebyone and Timbo. When people discuss the use of exceptions, usually someone eventually says: "Exceptions should be used in exceptional situations."

    As you can tell from the most of the answers here, if a constructor fails then the correct response is to throw an exception. However, in your case, it is not necessarily that you cannot create the object, it's more that you don't want to create it.

    Where the values are being read from an external source (eg. a file or a stream) there is a good chance that invalid values will be received and in that case, then it's not really an exceptional situation.

    Personally, I would lean towards validating the arguments before constructing the time object (something like Timbo's answer) and I would then have an assertion in the constructor to verify that they arguments are valid.

    In the case that your constructor needs a resource (eg. allocates memory) then that, IMHO, would be closer to an exceptional situation and so you would then throw an exception.

提交回复
热议问题