异常处理,c++中的意外终止符
exception handling, unexpected terminator in c++
下面的代码是关于异常处理的。我得到了输出:
Botch::f()
I'll be back!
为什么水果没有被捉住?谢谢!
忽略这一点。我想我已经提供了足够的细节。
#include <exception>
#include <iostream>
using namespace std;
void terminator() {
cout << "I'll be back!" << endl;
exit(0);
}
void (*old_terminate)() = set_terminate(terminator);
class Fruit {};
class Botch {
public:
void f() throw(Fruit, bad_exception) {
cout << "Botch::f()" << endl;
throw Fruit();
}
~Botch() { throw 'c'; }
};
int main() {
try{
Botch b;
b.f();
} catch(Fruit&) {
cout << "inside catch(Fruit)" << endl;
} catch(bad_exception&) {
cout << "caught a bad_excpetionfrom f" << endl;
}
}
因为在Fruit异常的堆栈展开期间,你抛出了另一个异常(来自Botch
析构函数)。所以你的终结者被叫来了。这就是为什么从析构函数抛出异常是一个坏主意,
Fruit
未被捕获,因为代码从未到达该catch子句。在main
的try
块中,对b.f()
的调用抛出了一个Fruit
类型的异常。作为响应,代码在进入catch子句之前销毁Botch
对象。Botch
的析构函数抛出另一个异常,触发对terminate
的调用。
在main中调用b.f()
时,会抛出一个Fruit
。然后执行离开try
块,在任何catch处理程序捕获Fruit
之前,b
被销毁,'c'
被抛出。当Fruit
仍然处于活动状态时抛出第二个异常将导致终止,而不管是否有任何catch处理程序。
这就是为什么永远不能抛出析构函数
因为程序流程如下:
try{
Botch b;
b.f();
//-> exception of class Fruit has been thrown
//-> Stack unwinding: during stack unwinding object b,
//which is on stack is destroyed, and its destructor is called
//-> this destructor ~Botch() { throw 'c'; } throws another exception
//and this caused call of your terminator()
} catch(Fruit&) { // so we are never here
相关文章:
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 在C++中对T*类型执行std::move的意外行为
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 我收到以下错误:抛出'std::bad_alloc'实例后终止调用
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 处理除以零会导致<csignal>意外行为
- vscode下的Arduino代码出现意外编译错误
- 使用++运算符会导致意外的结果
- 套接字读取后,我在缓冲区中看到意外输入
- 在C 中,可以检测到线程的意外终止
- 程序意外终止C
- 设置终止和意外处理程序
- 如何在 Google 测试中抑制终止时 assert() 意外触发
- 程序在引入 catch 块后意外终止
- 程序不断调用意外和终止函数
- 当循环意外终止时(C/C++)
- 在数组中增加元素时进程意外终止
- 异常处理,c++中的意外终止符
- Windows服务在Windows7中意外终止