异常处理
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关键字,程序不会产生异常
若抛出异常,则终止程序