C++ exception specification - handling not valid exceptions
-
15-06-2021 - |
Вопрос
What is the standard behavior in cases when function throws exception not in valid exception list ? For example when I run this code:
#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;
}
It behaves differently on GCC and Visual Studio C++ compilers:
- On VS 2010 not expected exception is catched in general exception handler.
- On GCC
unexpected()
handler function is called instead of catching exception.
Why is this difference ? Why MS C++ compiler doesn't calls unexpected()
callback ?
Решение
The documentation for set_unexpected
calls out this behaviour:
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.
Другие советы
Have you compiled with the right flags? Visual Studio has a default of not turning on exception handling for some optimised release builds.
You want /c and /EHsc
Не связан с StackOverflow