The Lazy Programmer

March 22, 2008

C++ Exception Specifications

Filed under: C#,Programming — ferruccio @ 4:44 pm
Tags: ,

Every once in a while C++ surprises me. Something that I thought I understood turns out not be exactly what I thought it was.

In C++, a function may have an exception specification which tells the compiler what exceptions the function may throw. e.g.

void test(void) throw(std::exception)

Tells the compiler that the function test() may throw an exception of type std::exception.

The function will compile and run fine whether or not you have the exception specification in the function signature. It will also work as expected whether or not it throws an exception. This lead me to believe that the exception specification was a hint to the compiler, telling it that the function may throw an exception, thus allowing the compiler to optimize the function as it saw fit.

I was completely wrong.

It turns out that exception specifications do tell the compiler what exceptions may be thrown by a function. But, if that function throws any other exception. Or, in fact, any function eventually called by the function with the exception specification throws any other exception, then the C++ run-time will call std::unexpected() whose normal behavior is to shut down the offending program.

I normally avoid using exception specifications in my own code, but sometimes you need to integrate with code that does use them. In these situations it pays to know what exception specifications really mean.

Some sites that I found useful while researching this issue:


Blog at

%d bloggers like this: