C++绝对不要在析构函数里面抛出异常(C++类相关)

1.抛出异常后可能无法执行之后释放资源的语句

2.C++无法处理同时抛出的两个异常,通常异常发生时,c++的机制会调用已经构造对象的析构函数来释放资源,此时若析构函数本身也抛出异常,则前一个异常尚未处理,又有新的异常,会造成程序崩溃的问题。

默认析构函数都有加noexcept,也可以强制无视noexcept抛出异常

class EvilB : public B{
	public:
	//~EvilB(){}
	~EvilB() noexcept(false) { throw std::string("error");}
};
void test(){
	try{
		EvilB b;
	}catch(std::string const& e){
		std::cout<<"catch you evil " << e << std::endl;
	}
}

基类和派生类同时抛出异常则程序会崩,一个catch无法同时捕获两个异常;

class B : public A {
	public:
		B(){}
		~B() noexcept(false) {
			std::cout<<"byebye B\n";
			throw std::string("error B");
		}
	private:
		std::string m_value;
}
class EvilB : public B {
	public:
	//~EvilB(){}
	~EvilB() noexcept(false) {throw std::string("error");}
};
void test(){
	try{
		EvilB b;
	}catch(std::string const& e){
		std::cout<<"catch you evil" << e << std::endl;
	}
}

定义两个相同类同时捕获一个异常程序也会崩

class B : public A {
	public:
		B(){}
		~B() noexcept(false) {std::cout<<"byebye B\n";}
	private:
		std::string m_value;
}
class EvilB : public B {
	public:
	//~EvilB(){}
	~EvilB() noexcept(false) { throw std::string("error");}
};
void test(){
	try{
		EvilB b;
		EvilB c;
	}catch(std::string const& e) {
		std::cout<<"catch you evil"<< e << std::endl;
	}
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值