Exception specification checked at *runtime*?

  • Thread starter Paul Brettschneider
  • Start date
P

Paul Brettschneider

Hello everyone,

I wanted to start adding exception specifications (via throw(...)) to a
project of mine, since it looked like a good idea for the sake of
documentation, giving optimisation-hints to the compiler and getting better
compiler warnings.

Much to my surprise, the following test program did not give warnings, when
compiled with gcc 4.1.3:

class exception {};

class x {
int a;
public:
void m1() throw();
void m2() throw( exception );
};

void x::m1() throw()
{
a = 1;
throw exception();
}

void x::m2() throw(exception)
{
a = 2;
}

I would have expected that, since x::m1() clearly throws an exception and
x::m2() clearly does not throw an exception, the compiler would give
warnings. I figure that in some cases giving this kind of warning would
be difficult (e.g. pointers to functions and methods or calling of functions
in legacy libraries without exception specification). But in 99% of the
cases this would have been a very nice feature, if used with care.

So I assumed an quality-of-implementation issue. But after a little
googeling I found this document: http://www.gotw.ca/publications/mill22.htm
which claims that the exception specification is checked at *runtime*.
And the following test program confirms this:

// With the classes from above
#include <iostream>
int main(int argc, const char **argv)
{
x X;
try {
X.m1(); X.m2();
} catch(exception &e) {
std::cout << "caught exception" << std::endl;
}

return 0;
}

Indeed, the compiler goes out of its way to catch the exception thrown by m1
and call std::terminate(). This seems insane for the following reasons:
* Runtime-overhead.
* Very un-C++. (e.g. const, private, etc.. is checked at compile-time, not
at run-time).
* Not what one would expect.

So, to make a long story short, my questions are:
Is this really what the standard says?
Why does the C++-faq not mention this?
Is there a plan for sensible exception specification, that is one that is
checked at compile time and that enables the compiler to do code
optimisation?

Thanks.

PS: Sorry if this was already discussed at length before, but I was quite
shocked by this behaviour.
 
N

Nemanja Trifunovic

So, to make a long story short, my questions are:
Is this really what the standard says?
Why does the C++-faq not mention this?
Is there a plan for sensible exception specification, that is one that is
checked at compile time and that enables the compiler to do code
optimisation?

I wrote about exception specifications in some detail here:
http://www.codeproject.com/cpp/stdexceptionspec.asp

But to make the long story short: yes, the exception specifications in
C++ are a run-time mechanism, and
to find out why, see here: http://www.bleading-edge.com/Publications/C++Report/v9607/Column2.htm
 
B

bjeremy

Hello everyone,

I wanted to start adding exception specifications (via throw(...)) to a
project of mine, since it looked like a good idea for the sake of
documentation, giving optimisation-hints to the compiler and getting better
compiler warnings.

Much to my surprise, the following test program did not give warnings, when
compiled with gcc 4.1.3:

class exception {};

class x {
int a;
public:
void m1() throw();
void m2() throw( exception );

};

void x::m1() throw()
{
a = 1;
throw exception();

}

void x::m2() throw(exception)
{
a = 2;

}

I would have expected that, since x::m1() clearly throws an exception and
x::m2() clearly does not throw an exception, the compiler would give
warnings. I figure that in some cases giving this kind of warning would
be difficult (e.g. pointers to functions and methods or calling of functions
in legacy libraries without exception specification). But in 99% of the
cases this would have been a very nice feature, if used with care.

So I assumed an quality-of-implementation issue. But after a little
googeling I found this document:http://www.gotw.ca/publications/mill22.htm
which claims that the exception specification is checked at *runtime*.
And the following test program confirms this:

// With the classes from above
#include <iostream>
int main(int argc, const char **argv)
{
x X;
try {
X.m1(); X.m2();
} catch(exception &e) {
std::cout << "caught exception" << std::endl;
}

return 0;

}

Indeed, the compiler goes out of its way to catch the exception thrown by m1
and call std::terminate(). This seems insane for the following reasons:
* Runtime-overhead.
* Very un-C++. (e.g. const, private, etc.. is checked at compile-time, not
at run-time).
* Not what one would expect.

So, to make a long story short, my questions are:
Is this really what the standard says?
Why does the C++-faq not mention this?
Is there a plan for sensible exception specification, that is one that is
checked at compile time and that enables the compiler to do code
optimisation?

Thanks.

PS: Sorry if this was already discussed at length before, but I was quite
shocked by this behaviour.

Ahh... exception specifications... there are a lot of reasons not to
love them, but you can probably google "C++ exception specifications"
and come up with a long list of other frustrated users. To your
problem, Exception Specifications in C++ do not work the way a lot of
people think they would. They are not checked exceptions (like java),
meaning there is no static time checking of exception specifications
w.r.t. the actual exceptions thrown... There are a couple of good
reasons for this i.e. for instance, for C++ code with exceptions to
play nicely with legacy code without.... I'm sure someone else will
jump in and tell how I missed the most important part or how its not
really correct and proceed to give you a nice lecture about the
history... but the short of it is, exceptions in C++ are checked only
at runtime... so if your code throws an exception that is not listed
in your exception specification you immediately jump to the global
unexpected() handler, whose default behavior is just to call
teminate() and end the process.
 
P

Paul Brettschneider

Nemanja said:
I wrote about exception specifications in some detail here:
http://www.codeproject.com/cpp/stdexceptionspec.asp

But to make the long story short: yes, the exception specifications in
C++ are a run-time mechanism, and
to find out why, see here:
http://www.bleading-edge.com/Publications/C++Report/v9607/Column2.htm

Thanks a lot. Now I understand where the standard authors come from, but I
do not completely agree with them. Yes, using compile-time exception
specification would incur development-overhead, but so does the use const.
What would be needed would be a quick way of telling the compiler that
certain exceptions won't happen. A good optimising compiler would even
realise that
for(int i = 0; i < v.size(); ++i) sum += v;
can't throw an out_of_range exception.

And, as opposed to Java, the feature is optional, just like const.

So we're left with a language-feature that should only be used sparingly and
which feels very un-C++. For the few cases where it is useful, it could
have been coded by hand. Oh well, at least no extra keyword was used. :(
 
B

Brendon Costa

I am getting around to releasing a notice on this list about it, but I
have developed a tool that performs static analysis of C++ exception
propagation. Including checking against the exception specs for
functions. This also takes into account function pointers, virtual
functions and a number of other situations.

Anyhow. If you are interested the website is:

http://edoc.sourceforge.net/

I am in the process of fixing a few things and then releasing a notice
on this list about it, but thought it was relevant to this discussion.

Thanks,
Brendon.
 
G

Guest

Hello everyone,

I wanted to start adding exception specifications (via throw(...)) to a
project of mine, since it looked like a good idea for the sake of
documentation, giving optimisation-hints to the compiler and getting better
compiler warnings.

It is my understanding that the use of exception specifications is
generally discouraged for a number of reasons, one of them being that it
does not give you any performance boost, on the contrary it can slow
your code down.

In the words of Herb Sutter:
<quote>
In brief, don't bother. Even experts don't bother.

Slightly less briefly, the major issues are:

Exception specifications can cause surprising performance hits, for
example if the compiler turns off inlining for functions with exception
specifications.

A runtime unexpected() error is not always what you want to have happen
for the kinds of mistakes that exception specifications are meant to catch.

You generally can't write useful exception specifications for function
templates anyway because you generally can't tell what the types they
operate on might throw.
</quote>

You can also read the Boost exception specification rationale on their
site: http://www.boost.org/more/lib_guide.htm#Exception-specification

I think the one exception to the rule is to use the empty exception
specification to indicate that no exceptions will ever be thrown.

For documentation a comment with the function will work just as well.
 
T

Tadeusz Kopec

Paul said:
Hello everyone,

I wanted to start adding exception specifications (via throw(...)) to a
project of mine, since it looked like a good idea for the sake of
documentation, giving optimisation-hints to the compiler and getting better
compiler warnings.

Good advice - don't do it. For the sake of documentation write comments
in the headers. Exception specification might not make the compiler make
more optimal code but rather the opposite - there will be added code to
check if your function throws exceptions which are not allowed and "beat
your program unconscious" if it does. It's one of the misfeatures of the
standard and should be avoided.
 
J

James Kanze

On 2007-11-01 20:38, Paul Brettschneider wrote:
It is my understanding that the use of exception
specifications is generally discouraged for a number of
reasons, one of them being that it does not give you any
performance boost, on the contrary it can slow your code down.
In the words of Herb Sutter:
<quote>
In brief, don't bother. Even experts don't bother.
Slightly less briefly, the major issues are:
Exception specifications can cause surprising performance
hits, for example if the compiler turns off inlining for
functions with exception specifications.

Bad compiler. Don't use it:).
A runtime unexpected() error is not always what you want to
have happen for the kinds of mistakes that exception
specifications are meant to catch.

The question is: what kinds of mistakes are exception
specifications meant to catch?
You generally can't write useful exception specifications for
function templates anyway because you generally can't tell
what the types they operate on might throw.

Again, the question is: what is a useful exception
specifications.
You can also read the Boost exception specification rationale
on their
site:http://www.boost.org/more/lib_guide.htm#Exception-specification
I think the one exception to the rule is to use the empty
exception specification to indicate that no exceptions will
ever be thrown.
For documentation a comment with the function will work just
as well.

It depends.

The general problem is that exception specifications (generally)
don't tell you enough to be useful. It's not enough to know
that a function might throw std::runtime_error; if you're
counting on it for error reporting, you need to know the
conditions under which it will throw it, and you need a
guarantee that it will actually throw it when those conditions
occur. Exception specifications don't help here; they don't
provide enough information.

The other thing you sometimes have to know is that certain
exceptions can't occur. Typically (and I've yet to find an
atypical case), this is only relevant if the set of exceptions
is all of them: in order to write correct exception safe code,
you need some operations which are guaranteed not to throw,
period, as part of their contract. An empty throw() documents
this very well, *and* enforces it. As such, it's quite
compatible with programming by contract, in which violations of
the contract result in an assertion failure. The important
thing is that when you see a throw() on a function, you know,
absolutely, that no exception will escape from that function; if
the author of the function makes an error, and does try to
propagate one, you get an abort(), exactly like you would if an
invariant check failed, or whatever.

This has nothing to do with performance. The question is
really: what are you using exceptions for? If the exception is
designed to propagate up through many layers of function calls,
then exception specifications are counter-productive: the whole
point of using exceptions is that the intermediate layers don't
need to know about the error conditions in the lower layers. If
the exception is designed to be processed immediately, by the
calling function, then return values are more appropriate---you
shouldn't be using exceptions anyway.
 
P

Paul Brettschneider

Erik said:
Hello everyone,

I wanted to start adding exception specifications (via throw(...)) to a
project of mine, since it looked like a good idea for the sake of
documentation, giving optimisation-hints to the compiler and getting
better compiler warnings.

It is my understanding that the use of exception specifications is
generally discouraged for a number of reasons, one of them being that it
does not give you any performance boost, on the contrary it can slow
your code down.
[...]
For documentation a comment with the function will work just as well.

Yes, but without compiler support (or tools like EDoc++) this is nearly
impossible to get right. Add an innocent string operation somewhere and a
whole slew of functions suddenly can throw std::badalloc. Which shows that
compile-time checking might really be tedious sometimes. But it could be
enhanced by differentiating between "maybe throws" and "does throw under
certain circumstances" and given that it isn't mandatory, it would add to
the language (in my case - I don't rely on external libraries - it
definitely would be useful).

What we have now is just syntactic sugar for a seldom used case.

I tried the g++ extension __attribute__((nothrow)) and this is just as
useless:

#define nothrow __attribute__((nothrow))
class exception {};
class x {
public:
void m1() nothrow { throw exception(); };
};

compiles without a warning. Or maybe even miscompiles if the compiler does
some optimisations on nothrow? :(
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,962
Messages
2,570,134
Members
46,690
Latest member
MacGyver

Latest Threads

Top