When is it right for a constructor to throw an exception?

前端 未结 24 977
时光取名叫无心
时光取名叫无心 2020-11-30 16:47

When is it right for a constructor to throw an exception? (Or in the case of Objective C: when is it right for an init\'er to return nil?)

It seems to me that a cons

24条回答
  •  青春惊慌失措
    2020-11-30 17:19

    Because of all the trouble that a partially created class can cause, I'd say never.

    If you need to validate something during construction, make the constructor private and define a public static factory method. The method can throw if something is invalid. But if everything checks out, it calls the constructor, which is guaranteed not to throw.

提交回复
热议问题