AndyMcoy
AndyMcoy

Reputation: 361

Why is std::unexpected() not called when I throw an exception in a function specified with an empty throw() specifier?

My understanding of the throw() specifier is that any exception types not listed in the specifier will cause a call to std::unexpected(), when thrown from within a given function. So I expect the output of the following code to be "unexpected called", but instead I see "Caught an exception". I'm compiling this with VS2013 which doesn't implement noexcept which is why I'm using throw().

#include <iostream>       
#include <exception>      

void testFunc() throw () {
    throw std::exception();
}

int main(void) {
    std::set_unexpected([](){
        std::cout << "unexpected called"; 
    });

    try {
        testFunc();
    }
    catch (...) {
        std::cerr << "Caught an exception"; 
    }

    return 0;
}

Why is std::unexpected not called?

Upvotes: 3

Views: 1208

Answers (1)

Christian Hackl
Christian Hackl

Reputation: 27548

https://msdn.microsoft.com/en-us/library/vstudio/wfa0edys%28v=vs.120%29.aspx says that:

Visual C++ departs from the ISO C++ Standard in its implementation of exception specifications.

[...]

[...] if an exception is thrown out of a function marked throw(), the Visual C++ compiler will not call unexpected [...].

[...]

Due to code optimizations that might be performed by the C++ compiler (based on the assumption that the function does not throw any C++ exceptions) if a function does throw an exception, the program may not execute correctly.

Additionally, in support of the above, https://msdn.microsoft.com/en-us/library/vstudio/awbt5tew.aspx says:

The C++ Standard requires that unexpected is called when a function throws an exception that is not on its throw list. The current implementation does not support this.

Upvotes: 2

Related Questions