|
Boost : |
From: Stephen Cleary (scleary_at_[hidden])
Date: 2000-03-20 10:50:57
dave abrahams wrote:
> What is the perceived benefit of using the empty
exception-specification?
>
The only benefit I can think of is a compiler that is working on a part
of code in a try block -- if it can determine that that code cannot
throw an exception, then the try/catches there can be removed. There
are *many* problems, though:
1) throw() will not guarantee that a function will not throw an
exception -- it just guarantees that a different course of action will
be taken. Because of this, throw() can only be used as a hint to the
compiler that the function *should* not throw an exception.
2) In order for throw() to be properly used as a hint, proper
programming practice is required (i.e., only throw exceptions listed in
the throw-spec), or else the compiler is just wasting its time.
3) On platforms that support faults as exceptions (meaning division
by zero, access violation/seg fault, etc.) it is often difficult or
impossible to predict whether exceptions of this type will be
(implicitly) thrown by any given piece of code.
4) The code that the compiler is working on is presumably part of a
try block; good programming practices will say that the only time to
have a try/catch block is in the case where a) it is possible to get an
exception, and b) we can recover from that exception. In other words,
with a good programmer, this optimization would be useless (IMO).
As is well-known, compilers can provide correct code just by wrapping
each call to a function-with-exception-spec inside a try/catch.
Furthermore, the except-spec *requires* these compilers to either
provide the implicit try/catch or do something like the above.
Based on the complexity of implementing such an optimization, and (by
(4)) the probable uselessness of it, I don't think we will see it
anytime soon.
I believe that proper documentation will *always* include exception
specifications, but that proper code never will [1].
OTOH, I do see a possible usage for except-spec; namely, when debugging
your code. I've never used it in this way, and its usefulness would be
determined by platform specifics; but it might be helpful in finding
unexpected (!) exceptions.
Just my $0.02 :)
-Steve
[1] No, not even operator T*() { return ptr; }. Consider contrived
example:
int * tmp = (shared_ptr<int> *)(0)->operator int *(); // may throw
access violation/seg fault
Now, of *course* no programmer would write such code, but the compiler
cannot predict that "this" *isn't* some invalid value, so it must err
on the side of caution.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk