『C++学习录』异常处理

异常处理

1.异常处理

错误检测

throw关键字抛出异常

异常Exception

错误处理

捕获异常并处理,try/catch块

2.throw表达式

throw对象/数据

//无异常处理版本
int divide(int d1,int d2){
	if(d2 = =0)
		return -1;//有问题,碰巧返回值为-1??
	return d1/d2;
}
//有异常处理
int divide(int d1,int d2){
	if(d2 = =0)
		throw runtime_error("d2 is zero!");//抛出异常
		//或者throw 0;
	return d1/d2;
}

3.标准异常

Bad_cast

bad_alloc

runtime_error

logic_error

虚成员函数

virtual const char* what() const noexcept;

4.自定义异常

class MyException : public runtime_error{

public:

​ explicit MyException(const string &s) : runtime_error(s){}

};

5.try/catch块

try{

代码,可能会Throw异常

异常可在嵌套的函数调用中产生

}

catch(异常说明符1){

​	异常类型1的处理代码块

}

catch(异常说明符2){

​	异常类型2的处理代码块

}

catch(...){//捕获一切正常

}

6.编写异常处理代码

try{
	divide(8,2);
}catch(runtime_error & err){
	cout<<err.what()<<endl;
	exit(1);
}

7.重新抛出异常

try{
	divide(8,2);
}catch(runtime_error & err){
	cout<<err.what()<<endl;
	throw;
}//完成部分处理,重新抛出异常

8.捕捉所有异常

try{

}catch(...){

}

9.catch的匹配顺序

特定类型靠前,通用类型靠后

try{

}catch(std::bad_cast&e2){

}catch(std::exception&e1){

}catch(...){

}

10.禁止异常处理机制

noexcept关键字,程序不会产生异常

若抛出异常,则终止程序

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值