//自定义异常类
class CDivZeroException //除零异常类
{
public:
char ExceptionMsg[128];
CDivZeroException(){
strcpy_s(ExceptionMsg,"除零错误"); //设置异常信息
}
};
class CNegException
{
public:
char ExceptionMsg[128];
CNegException(){
strcpy_s(ExceptionMsg, "除数为负数错误"); //设置异常信息
}
};
//定义一个除法函数
bool Div(int nDiv, int nDivisor, int &nRet){
try{
if (nDivisor == 0)
throw CDivZeroException(); //抛出异常
else if (nDivisor < 0)
throw CNegException();
}
catch (CDivZeroException e) //捕捉异常
{
cout << e.ExceptionMsg << endl;
return false;
}
catch (CNegException e)
{
cout << e.ExceptionMsg << endl;
return false;
}
return true;
}
int main()
{
int nRet;
bool bRet = Div(100, -3, nRet);
cin.get();
return 0;
}
原文:http://www.cnblogs.com/smile-yun/p/3789121.html