在c++语言中,为了处理异常,提供了try、catch、throw等关键字,其中try存放的是可能出现异常的语句,catch里包含的是处理异常的方法,而throw关键词是手动触发异常,下面举个简单的例子了解一下具体的使用效果
#include<iostream>
#include<string>
using namespace std;
class CDivZeroException{
public:
char ExceptionMsg[128];
CDivZeroException(){
strcpy(ExceptionMsg,"除零错误");
}
};
class CNegException{
public:
char ExceptionMsg[128];
CNegException(){
strcpy(ExceptionMsg,"负数错误");
}
};
bool Div(int x,int y,int& ret){
try{
if(y==0)
throw CDivZeroException();
if(y<0)
throw CNegException();
else
ret=x/y;
}
catch(CDivZeroException e){
cout<<e.ExceptionMsg;
}
catch(CNegException e){
cout<<e.ExceptionMsg;
}
return true;
}
int main(){
int ret;
Div(20,0,ret);
return 0;
}
除零错误请按任意键继续. . .