When is it right for a constructor to throw an exception

constructorexceptionlanguage-agnostic

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 constructor should fail — and thus refuse to create an object — if the object isn't complete. I.e., the constructor should have a contract with its caller to provide a functional and working object on which methods can be called meaningfully? Is that reasonable?

Best Solution

The constructor's job is to bring the object into a usable state. There are basically two schools of thought on this.

One group favors two-stage construction. The constructor merely brings the object into a sleeper state in which it refuses to do any work. There's an additional function that does the actual initialization.

I've never understood the reasoning behind this approach. I'm firmly in the group that supports one-stage construction, where the object is fully initialized and usable after construction.

One-stage constructors should throw if they fail to fully initialize the object. If the object cannot be initialized, it must not be allowed to exist, so the constructor must throw.