为什么不调用函数unexpected
Why the function unexpected is not called?
我希望下面的代码调用我的unexpected处理程序,但是我的terminate处理程序被调用了:
#include <except>
#include <iostream>
void my_terminate() {
std::cerr << "my terminate handler";
std::exit(0);
}
void my_unexpected() {
std::cerr << "my unexpected handler";
std::exit(EXIT_FAILURE);
}
#pragma argsused
int main(int argc, char* argv[])
{
std::set_terminate(my_terminate);
std::set_unexpected(my_unexpected);
try {
throw std::exception();
} catch (const std::logic_error&) {
}
return 0;
}
c++ Builder 6开发者指南明确鼓励通过set_unexpected()
安装自定义的意外处理程序。我做错了什么,或者这只是c++ -Builder 6中的一个bug ?
当抛出意外异常时,调用std::set_unexpected
(对于std::unexpected
)设置的处理程序将被调用;当异常未处理时就不会。当违反动态异常规范时,调用意外处理程序。
举例;
void my_terminate() {
std::cerr << "my terminate handler";
std::exit(0);
}
void my_unexpected() {
std::cerr << "my unexpected handler";
std::exit(EXIT_FAILURE);
}
void function() throw() // no exception in this example, but it could be another spec
{
throw std::exception();
}
int main(int argc, char* argv[])
{
std::set_terminate(my_terminate);
std::set_unexpected(my_unexpected);
try {
function();
} catch (const std::logic_error&) {
}
return 0;
}
输出为
my unexpected handler
std::set_terminate
设置的处理程序由std::terminate
调用(由于参考中列出的许多原因)。这里有趣的是,当抛出异常但未捕获时,默认行为是调用std::terminate
。
当发生未捕获的异常时,调用 terminate
int main()
{
throw 1; // terminate
}
发生意外异常时,调用 unexpected
。
void foo() throw(int)
{
throw "unexpected will be called.";
}
int main()
{
foo();
}
我将向您展示发生terminate/unexpected的示例程序:
#include <cstdlib>
#include <iostream>
#include <exception>
#define TEST_TERMINATE
void my_terminate()
{
std::cout << "terminate!" << std::endl;
std::abort();
}
void my_unexpected()
{
std::cout << "unexpected!" << std::endl;
std::abort();
}
void foo() throw(int)
{
throw "unexpected will be called.";
}
int main()
{
std::set_terminate(my_terminate);
std::set_unexpected(my_unexpected);
#ifdef TEST_TERMINATE
throw 1;
#else
foo();
#endif
}
(终止的实例,unexpected)
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 构造函数和析构函数之间的"unexpected"配对。为什么要这样工作?
- 为什么当我在使用空 throw() 说明符指定的函数中抛出异常时没有调用 std::unexpected()
- 为什么不调用函数unexpected