c++ - 当我在用空 throw() 说明符指定的函数中抛出异常时,为什么不调用 std::unexpected()?

标签 c++ exception visual-studio-2013

我对 throw() 说明符的理解是,任何未在说明符中列出的异常类型在从给定函数内抛出时都会导致调用 std::unexpected()。 所以我希望以下代码的输出是“意外调用”,但我看到的却是“捕获到异常”。我正在用 VS2013 编译它,它没有实现 noexcept,这就是我使用 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;
}

为什么不调用 std::unexpected?

最佳答案

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

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.

此外,为支持上述内容,https://msdn.microsoft.com/en-us/library/vstudio/awbt5tew.aspx说:

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.

关于c++ - 当我在用空 throw() 说明符指定的函数中抛出异常时,为什么不调用 std::unexpected()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29064666/

相关文章:

c++ - 在C++11或更高版本中,有没有办法通过lambda实现单方法纯虚C++接口(interface)?

c++ - Qt 无法编译(10.5 Intel Mac)

java - 尽管有 Try/Catch,Android 应用还是崩溃了

java - 使用 JMAP 进行堆转储时出现异常

visual-studio-2012 - 使用 VS2013 在 TFS 中进行时间跟踪

c++ - 在 C++ 中传递专门的函数指针

c++ - 使用连接器 c++ 访问 MYSQL 数据库(如何添加到我的标准搜索目录的路径)

Powershell 捕获异常类型

mysql - vb.net 代码可以在本地运行,但不能在 Web 服务器上运行

c++ - 如何创建简单的 2D 隐形传送?