Re: Exceptions in destructors
On Apr 30, 7:30 am, Rennie deGraaf <degr...@cpsc.no-processed-
pork.ucalgary.ca> wrote:
[...]
In other words, I really should add throw specifiers, like this:
struct Foo
{
void finalize() throw(double)
{
throw 1.0;
}
~Foo() throw()
{
try
{
finalize();
}
catch (double d)
{}
}
};
I suppose that it would generally be a good idea to /always/ tag my
destructors with throw() unless I have a good reason to do otherwise?
For that matter, are there any circumstances where it would be safe to
throw an exception from a destructor?
Opinions with regards to the utility of exception specifiers
vary:-). In general, there's pretty much a consensus that
specifiers which list possible exceptions are useless; the only
possible effect they can have is to result in slower code.
There's much less consensus regarding empty specifiers, e.g.
throw(); knowing that a function cannot throw is often important
information, both to the user and to the optimizer.
In practice, with regards to the reader, I would generally
expect a destructor not to throw, and any other function to
throw std::exception, or anything derived from it, unless
otherwise documented. Throwing from a destructor should be so
exceptional that not just the possibility itself, but the
justification and reasons behind it should be documented; an
exception specifier is not sufficient for this. And because
non-throwing destructors are so common, you can certainly not
count on the absense of a specifier on the destructor to signal
that it might throw. So from the human reader's point of view,
an exception specifier on a destructor doesn't really add any
useful information. Just the reverse is true for other
functions, however; in the absense of other documentation, you
should assume that the function can throw. And a simple
"throw()" is excellent documentation that it cannot. Unlike the
case for destructors, I don't think you normally have to justify
why the function doesn't throw; it's sufficient to document
clearly that it doesn't.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34