为什么当我在用空 throw() 说明符指定的函数中抛出异常时不调用 std::unexpected()?
Why is std::unexpected() not called when I throw an exception in a function specified with an empty throw() specifier?
我对 throw() 说明符的理解是,任何未在说明符中列出的异常类型在从给定函数内抛出时都会导致调用 std::unexpected()。
所以我希望下面代码的输出是 "unexpected called",但我看到的却是 "Caught an exception"。我正在用没有实现 noexcept
的 VS2013 编译它,这就是我使用 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.
我对 throw() 说明符的理解是,任何未在说明符中列出的异常类型在从给定函数内抛出时都会导致调用 std::unexpected()。
所以我希望下面代码的输出是 "unexpected called",但我看到的却是 "Caught an exception"。我正在用没有实现 noexcept
的 VS2013 编译它,这就是我使用 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 callunexpected
[...].[...]
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.