[Exceptional C++ Style] Item 13: A Pragmatic Look at ExceptionSpecifications

Paul Grenyer paul at paulgrenyer.co.uk
Tue Dec 7 05:59:55 EST 2004


Hi All

Thanks to David for another fine summary!

> An exception spscification tells the compiler to do a run-time check that
> guarantees that only exceptions of certain types will be throw. If the
> guarantee is violated, the function unexpected is called. The
specification
> below gurantees that function f will emit only exceptions of type A or B.

This is the bit that surprised me. I thought, previously, that exception
specifications were enforced at compile time in a similar way to const. This
belief  inspired by MSVC giving me warnings  in certain conditions. Eg:

#include <memory>

void MyFunc() throw()
{
     throw std::bad_alloc();
}

int main()
{
     MyFunc();
     return 0;
}

main.cpp(6) : warning C4297: 'MyFunc' : function assumed not to throw an
exception but does
        __declspec(nothrow) or throw() was specified on the function

I just assumed it wasn't an error due to MSVC inadequacy. It now appears
that MSVC is inline with the standard and "extra" helpful.

I think it would be better if exception specifications were enforced at
compile time. What do people think?

> - Some compilers will not inline a function with a performance
> specification.

Should that be "...with an exception specification"?

> - Do not use exception specifications.

What about swap functions? For example Herbs copy-swap idiom for class
copy-constructors and assignment operators? Should the swap function there
be marked with throw()? Even as just as documentation to the user for
reassurance?

Regards
Paul

Paul Grenyer
email: paul at paulgrenyer.co.uk
web: http://www.paulgrenyer.co.uk
articles: http://www.paulgrenyer.dyndns.org/articles/

I put my hand upon the lever, said let it rock and let it roll.




More information about the Effective-cpp mailing list