Kai-Uwe Bux said:
Throwing from a constructor is fine. The alternative is to have the
constructor leave the object in an inconsistent state, which is rarely the
better way to go about the problem.
Right, as usual. To back you up, here's a quote from _C++ Coding
Standards_ by Sutter and Alexandrescu, Item 72:
"Exception handling is better than the alternatives for reporting
errors from constructors and operators: The copy constructors and the
operators have predefined signatures that leave no room for return
codes. In particular, constructors have no return type at all (not even
void), and and for example every operator+ must take exactly two
parameters and return one object (of a prescribed type; see Item 26).
For operators, using error codes is at least possible if not desirable;
it would require errno-like approaches, or inferior solutions like
packaging status with an object. For constructors, using error codes is
not feasible because the C++ language tightly binds together
constructor exceptions and constructor failurs so that the two have to
be synonymous; if instead we used an errno-like approach such as
SomeType anObject; //Construct an object
// Test whether construction worked
if( SomeType::ConstructionWasOk() ) {
// ...
then not only is the result ugly and error-prone, but it leads to
misbegotten objects that don't really satisfy their type's
invariants--never mind the race conditions inherent in calls to
SomeType::ConstructionWasOk in multithreaded applications. (See
[Stroustrup00] §E.3.5.)"
BTW, that section in Stroustrup can be found here for free:
http://www.research.att.com/~bs/3rd_safe.pdf
See also this GotW:
http://www.gotw.ca/gotw/066.htm
Cheers! --M