Re: throwing exceptions from constructor and other alternatives
David Abrahams wrote:
"kanze" <email@example.com> writes:
There is no contention on the fact that "Throwing
exceptions is the only good way to signal an error during
construction" - my point was only that of "Do we need to
design classes that depend on ctors throwing up"...
It seems to me that this boils down to: "Should we avoid
designing classes which guarantee invariants which cannot be
proven to hold at compile time?" If we avoid throwing
constructors entirely, we limit ourselves to class
invariants which can be checked at compile time.
Not really. We can always use assert, and abort if the class
cannot respect its invariants.
Yeah, but that turns the conditions for establishing the
invariant into preconditions...
If it is reasonably possible for the user to verify before
hand that his proposed arguments will allow the class to
respect its invariants, then this can even be a preferred
alternative. Such checks are not always possible, however,
and even when possible, may have unacceptable overhead.
....which is why it may be a bad idea to make them
preconditions. So you're left with either exceptions, or
weakening the class invariants.
Ideally, most of the time, they probably should be
preconditions. If you don't have the necessaries to create an
object, don't. In practice, this often creates more problems
than it is worth, of course, and exceptions are the lesser of
Consider the simple example of an IP class, which has a
constructor from a string. At my last client site, I
implemented such -- and made it a pre-condition that the string
had the legal format. This meant that 1) I also had to provide
a static member function to test it, and 2) most of the time,
the code would try to match the regular expression twice, once
in the static isValid function, and a second time in the assert
in the constructor. The first is not really a problem; it
doesn't mean any duplication of code, because of course, the
constructor also called the static function. The second, on the
other hand, can have a significant impact on performance. In my
case, no problem: the only time we actually constructed IP's
from strings was when reading the configuration file, a total of
five or six times at program start up. Not ever program has it
so simple, however, and leaving all checking until the
constructor, and then raising an exception, is certainly a lot
faster. Even if it is a question of a syntax error which you
would normally expect to be handled not to far from the place
where it was detected.
James Kanze firstname.lastname@example.org
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]