当函数抛出不在有效异常列表中的异常时,标准行为是什么?例如,当我运行这段代码时:
#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 上,一般异常处理程序未捕获预期的异常。
- 在 GCC 上调用
unexpected()
处理函数而不是捕获异常。
为什么会有这种差异?为什么 MS C++ 编译器不调用 unexpected()
回调?
最佳答案
The documentation for set_unexpected
调用此行为:
Remarks
...
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++ 异常规范 - 处理无效异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11097513/