1、引发异常
由除0的错误导致异常。
#include "stdafx.h"
#include "iostream.h"
int main(int argc, char* argv[])
{
int nDiv = 100; //定义一个整型变量,初始化为100
int nDivisor = 0; //定义一个整型变量,初始化为0
int nRet = nDiv / nDivisor; //进行除法运算
cout << nRet << endl; //输出结果
return 0;
}
2、捕获异常
异常被捕获,程序并未中断。
#include "stdafx.h"
#include "iostream.h"
int main(int argc, char* argv[])
{
try //捕捉异常
{
int nDiv = 100; //定义一个整型变量,初始化为100
int nDivisor = 0; //定义一个整型变量,初始化为0
int nRet = nDiv / nDivisor; //进行除法运算
cout << nRet << endl; //输出结果
}
catch(...) //处理异常
{
cout << "产生异常!" << endl;
}
return 0;
}
3、抛出异常
在程序中,异常语句通常出现在try语句块中,当程序运行到throw语句时,后面的代码不会被执行,而是跳到catch语句块中。
#include "stdafx.h"
#include "iostream.h"
int main(int argc, char* argv[])
{
try
{
int nDiv = 100; //定义一个整数,初始化为100
int nDivisor = 0; //定义一个整数,初始化为0
if (nDivisor <= 0) //如果除数小于等于0
{
throw "除数必须大于0!"; //抛出异常
}
int nRet = nDiv / nDivisor; //进行触发运算
cout << nRet << endl;
}
catch(...) //异常捕捉
{
cout << "运算失败!" << endl;
}
return 0;
}
4、自定义异常类
下面代码定义了两个异常,一个除0的异常类,一个负数异常类。
#include "stdafx.h"
#include "iostream.h"
#include "string.h"
class CDivZeroException //定义一个除零的异常类
{
public:
char ExceptionMsg[128]; //定义数据成员
CDivZeroException() //定义构造函数
{
strcpy(ExceptionMsg,"除零错误"); //设置异常信息
}
};
class CNegException //定义一个负数异常类
{
public:
char ExceptionMsg[128]; //定义数据成员
CNegException() //定义构造函数
{
strcpy(ExceptionMsg,"除数为负数错误"); //设置异常信息
}
};
bool Div(int nDiv ,int nDivisor, int &nRet) //定义除法函数
{
try //异常捕捉
{
if (nDivisor == 0) //判断除数是否为0
throw CDivZeroException(); //抛出异常
else if ( nDivisor < 0) //判断除数是否为负数
throw CNegException(); //抛出异常
else
nRet = nDiv / nDivisor; //进行除法运算
}
catch(CDivZeroException e) //捕捉除零的异常
{
cout << e.ExceptionMsg << endl; //输出异常信息
return false;
}
catch(CNegException e) //捕捉除数为负数的异常
{
cout << e.ExceptionMsg << endl; //输出异常信息
return false;
}
return true;
}
int main(int argc, char* argv[])
{
int nRet; //定义一个变量
bool bRet = Div(100, -2, nRet); //调用Div函数
return 0;
}