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

前端 未结 24 989
时光取名叫无心
时光取名叫无心 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:21

    Throw an exception if you're unable to initialize the object in the constructor, one example are illegal arguments.

    As a general rule of thumb an exception should always be thrown as soon as possible, as it makes debugging easier when the source of the problem is closer to the method signaling something is wrong.

提交回复
热议问题