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

前端 未结 24 926
时光取名叫无心
时光取名叫无心 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条回答
  •  -上瘾入骨i
    2020-11-30 17:27

    You absolutely should throw an exception from a constructor if you're unable to create a valid object. This allows you to provide proper invariants in your class.

    In practice, you may have to be very careful. Remember that in C++, the destructor will not be called, so if you throw after allocating your resources, you need to take great care to handle that properly!

    This page has a thorough discussion of the situation in C++.

提交回复
热议问题