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

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

    I'm not sure that any answer can be entirely language-agnostic. Some languages handle exceptions and memory management differently.

    I've worked before under coding standards requiring exceptions never be used and only error codes on initializers, because developers had been burned by the language poorly handling exceptions. Languages without garbage collection will handle heap and stack very differently, which may matter for non RAII objects. It is important though that a team decide to be consistent so they know by default if they need to call initializers after constructors. All methods (including constructors) should also be well documented as to what exceptions they can throw, so callers know how to handle them.

    I'm generally in favor of a single-stage construction, as it's easy to forget to initialize an object, but there are plenty of exceptions to that.

    • Your language support for exceptions isn't very good.
    • You have a pressing design reason to still use new and delete
    • Your initialization is processor intensive and should run async to the thread that created the object.
    • You are creating a DLL that may be throwing exceptions outside it's interface to an application using a different language. In this case it may not be so much an issue of not throwing exceptions, but making sure they are caught before the public interface. (You can catch C++ exceptions in C#, but there are hoops to jump through.)
    • Static constructors (C#)

提交回复
热议问题