H
Herb Sutter
Jens Theisen said:Stuart Golodetz said:Whether exception specifications are a good thing or not is certainly up for
discussion What I don't understand though is what purpose is served by
enforcing them at runtime. If you're going to enforce them, surely it should
be at compile-time? I was just wondering if there's some technical
difficulty making that impossible, or at any rate very hard?
I disagree with the other answers to your question - I find exception
specifications almost useless for that reason; and in practice, indeed
most people don't use them. To quote Herb Sutter: [...]
If someone know why exception specifications are as brain-dead as they
are in C++, I'd be intruiged to hear. My guess is some compatibility
rationale.
Essentially, exception specifications are a wonderful idea in basic
principle, but no one really knows how to design them.
There are two major approaches, and both have serious problems. Java chose
static enforcement (at compile time, as suggested above), and C++ chose
dynamic enforcement. Interestingly, I see Java people ask "why not enforce
these dynamically?" about as often as I see C++ people ask "why not
enforce these statically?"
Briefly:
When you go down the Java path, people love exception specifications until
they find themselves all too often encouraged, or even forced, to add
"throws Exception," which immediately renders the exception specification
entirely meaningless. (Example: Imagine writing a Java generic that
manipulates an arbitrary type T...)
When you go down the C++ path, people love exception specifications until
they discover that violating one means invoking terminate, which is almost
never what you want.
For more, see:
"A Pragmatic Look At Exception Specifications"
C/C++ Users Journal, 20(7), July 2002.
http://www.gotw.ca/publications/mill22.htm
particularly the "Issue the Second" subhead.
Herb