1

当函数抛出不在有效异常列表中的异常时,标准行为是什么?例如,当我运行此代码时:

#include <iostream>
#include <cstdlib>

using namespace std;

void NotLegal() throw(char) {
    throw 42;
}

void myunexpected () {
  cout << "exception not in list\n";
  cin.get();
  exit(0);
}

int main()
{
    set_unexpected(myunexpected);

    try {
       NotLegal();
   }
   catch(...) {
       cout << "exception catched";
       cin.get();
   }

   return 0;
}

它在 GCC 和 Visual Studio C++ 编译器上的行为不同:

  • 在 VS 2010 上,一般异常处理程序中未捕获到预期异常。
  • 调用GCCunexpected()处理函数而不是捕获异常。

为什么会有这种差异?为什么 MS C++ 编译器不调用unexpected()回调?

4

2 回答 2

3

的文档set_unexpected调用了这种行为:

评论

...

C++ 标准要求unexpected在函数抛出不在其抛出列表中的异常时调用它。当前的实现不支持这一点。

于 2012-06-19T09:10:52.937 回答
1

您是否使用正确的标志进行了编译?Visual Studio 默认情况下不为某些优化的发布版本打开异常处理。

你想要/c 和 /EHsc

于 2012-06-19T08:49:33.100 回答