Contents Up << >>

How can I handle a constructor that fails?

Throw an exception.

Constructors don't have a return type, so it's not possible to use error codes. The best way to signal constructor failure is therefore to throw an exception.

Before C++ had exceptions, we signaled constructor failure by putting the object into a "half-baked" state (e.g., by setting an internal status bit). There was a query ("inspector") method to check this bit, that allowed clients to discover whether they had a live object. Other member functions would also check this bit, and, if the object wasn't really alive, do a no-op (or perhaps something more obnoxious such as "abort()"). This was really ugly.