Re: throwing exceptions from constructor and other alternatives
johnchx2@yahoo.com wrote:
kanze wrote:
Not really. We can always use assert, and abort if the class
cannot respect its invariants. 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.
I'm not sure I see when abort would be preferable to throwing
an exception. Can you elaborate or illustrate?
Anytime you violate a precondition, or otherwise find a
programming error. Exceptions are designed for cases where you
can abort some part of the processing without affecting the rest
of the program -- for example, in a server, you might abort
processing a request because it was too complicated (and
resulted in bad_alloc), but that doesn't mean you have to refuse
all future requests (supposing, of course, that you backed out
of the aborted request correctly).
If you detect a programming error, this is NOT the case --
there's no way to back out and correct the code. So about all
you can reasonably do is abort.
(Also, do those who object to constructors that throw find
aborting a preferable alternative?)
That's a different question. I use three types of error
reporting: return codes, exceptions and aborting. Return codes,
when the error is more or less to be expected from time to time
in the course of normal processing, and it is reasonable to
think that at least in some cases, it can be handled
immediately ; exceptions, when the error probably won't normally
occur, or signifies a problem at a higher level, which almost
certainly requires backing out of a complex operation, and abort
when I detect an "impossible" condition -- something which
logically couldn't have happened. Furthermore, I'll sometimes
use exceptions in the first case, particularly if the error
would normally be detected in a constructor -- it's nice to say
that a return code would be ideal, but constructors don't have
return codes, and even if they did, you would still be left with
an object in an incoherent state.
--
James Kanze kanze.james@neuf.fr
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! ]