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

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

    It's always pretty dodgy, especially if you're allocating resources inside a constructor; depending on your language the destructor won't get called, so you need to manually cleanup. It depends on how when an object's lifetime begins in your language.

    The only time I've really done it is when there's been a security problem somewhere that means the object should not, rather than cannot, be created.

提交回复
热议问题