I know this is a valid c++ program. What is the point of the throw in the function declarement? AFAIK it does nothing and isnt used for anything.
#include <exception>
void func() throw(std::exception) { }
int main() { return 0; }
I know this is a valid c++ program. What is the point of the throw in the function declarement? AFAIK it does nothing and isnt used for anything.
#include <exception>
void func() throw(std::exception) { }
int main() { return 0; }
It specifies that any
std::exception
can be thrown fromfunc()
, and nothing else. If something else is thrown, it will call anunexpected()
function which by default callsterminate()
.What this means is that throwing something else will almost certainly terminate the program, in the same manner as an uncaught exception, but the implementation will have to enforce this. This is normally much the same as putting a
try{...}catch(){...}
block aroundfunc()
, which can inhibit performance.Usually, exception specifications aren't worth it, according to the Guru of the Week column about it. The Boost guidelines say that there might be a slight benefit with a blank
throws()
for a non-inline function, and there are disadvantages.Basically this:
Is just shorthand fro this:
Calling terminate() is rarely what you want, as the stack is not unwound and thus all your efforts in RAII is wasted. The only exception to the rule is declaring an empty throw list and this is mainly for documentation purposes to show that you are supporting the no-throw exception gurantee (you should still manually catch all exceptions in this situation).
Some important (imho) places that should be no-throw are destructors and swap() methods. Destructors are rarely explicitly marked no-throw but swap() are quite often marked no-throw.
Exception specification. The type(s) following the
throw
keyword specifies exactly what all, if any, exceptions the function can throw. See 15.4 of the draft.Note: A function with no exception-specification allows all exceptions. A function with an empty exception-specification,
throw()
, does not allow any exceptions.This is an exception specification. It says that the only exception that func() can throw is std::exception (or a derivative thereof). Attempting to throw any other exception will give std::unexpected instead.
That is an exception specification, and it is almost certainly a bad idea.
It states that
func
may throw astd::exception
, and any other exception thatfunc
emits will result in a call tounexpected()
.This is a C++ exception specification. It declares that the particular function will potentially throw a
std::exception
type.In general though exception specifications in C++ are considered a feature to avoid. It's an odd feature in that it's behavior is declared at compile time but only checked at runtime (very different from say Java's version).
Here is a good article which breaks down the feature