在程序运行时,可能会有一些隐藏的bug突然爆发,导致程序崩溃。遇到这样的情况调试起来难度较大,因此C++提供了一种异常不住抛出机制,在不确定安全或者怀疑有重大隐患的代码块前面加上try关键字,后面使用catch关键字捕捉,如果捕捉到异常,可以在catch代码块中使用throw关键字抛出异常。
用法如下:
try
{
throw 类型//如果是这种异常就抛出这种类型的数据类型
//可能抛出异常的语句
};
catch(异常类型1,异常对象1)
{
//针对异常类型1的异常处理
}
catch(异常类型2,异常对象2)
{
//针对异常类型2的异常处理
}
catch(....)
{
//针对其他异常类型的异常处理
}
用法如下:
try
{
throw 类型//如果是这种异常就抛出这种类型的数据类型
//可能抛出异常的语句
};
catch(异常类型1,异常对象1)
{
//针对异常类型1的异常处理
}
catch(异常类型2,异常对象2)
{
//针对异常类型2的异常处理
}
catch(....)
{
//针对其他异常类型的异常处理
}
例如:
#include<iostream>
using namespace std;
class A
{
private:
int m_a;
public:
A()
{
cout << "constructor" << endl;
m_a = 4;
}
~A()
{
cout << "xigouhanshu" << endl;
}
};
int Div(int a, int b)throw(int,char);//声明了的抛出类型下面一定要实现捕捉到他的程序,否则默认程序终止
int Div(int a,int b)throw(int,char)
{
A t;
if (0 == b)
{
throw 1;
}
if(0==a)
{
throw 'a';
}
else
{
return a / b;
}
}
int main()
{
int a, b;
cout << "请输入a和b的值" << endl;
cin >> a >> b;
try
{
cout << Div(a,b) << endl;
}
catch (int)//获得了错误后的处理
{
cout << "被除数为零" << endl;
}
catch(char)
{
cout << "dasd" << endl;
}
return 0;
}
当b=0时try程序段会抛出int型异常,不论throw与catch之间隔了多少层函数还是嵌套,他抛出的异常都会被catch接收到而int型异常会被下面的catch(int)接受到并做处理,在处理未完成之前程序就会一直停滞在这个地方,但在C++中基本数据类型虽然只有几种,但是我们可以创建自己的类来记录各种各样的错误类型
#include<iostream>
using namespace std;
class Array
{
private:
int length;
int *data;
public:
class Error//基类,下面所有的错误类型都是由此类派生出来的
{
protected:
const char *ErrMsg;//错误原因
public:
Error(const char *ptr):ErrMsg(ptr)
{
}
virtual const char *GetE() = 0;//获取错误原因的纯虚函数
};
class eNegetive : public Error
{
public:
eNegetive() : Error("eNegetive")//数组长度为负数的错误
{
}
const char *GetE()
{
return ErrMsg;
}
};
class eZero : public Error
{
public:
eZero() : Error("eZero")//数组长度为0的错误
{
}
const char *GetE()//对基类虚函数的重写
{
return ErrMsg;
}
};
class eTooSmall : public Error
{
public:
eTooSmall() : Error("eTooSmall")//数组长度太小的错误
{
}
const char *GetE()
{
return ErrMsg;
}
};
class eTooBig : public Error
{
public:
eTooBig() : Error("eTooBig")数组长度太大的错误
{
}
const char *GetE()
{
return ErrMsg;
}
};
Array(int l);//对数组类的构造函数
int &operator[](int index);//数组下表[]的重载
~Array();
};
Array::Array(int l)
{
length = l;
if(l<0)//针对不同的错误类型扔出不同的数据类型
{
throw eNegetive();
}
if(l==0)
{
throw eZero();
}
if(l>0&&l<10)
{
throw eTooSmall();
}
if(l>10000)
{
throw eTooBig();
}
data = new int[length];//如果无措的话进行这一步
}
Array::~Array()
{
if(data!=NULL)
{
delete data;
data = NULL;
}
}
int &Array::operator [](int index)
{
return data[index];
}
int main()
{
try
{
Array a(50000);
}
catch(Array::eNegetive &e)
{
cout << e.GetE() << endl;
}
catch (Array::eZero &e)
{
cout << e.GetE() << endl;
}
catch (Array::eTooSmall &e)
{
cout << e.GetE() << endl;
}
catch (Array::eTooBig &e)
{
cout << e.GetE() << endl;
}
return 0;
}
在C++中出了可以自己定义新的数据类型用来保存错误类型,还可以使用他提供的基类exception,在exception中有个纯虚what()函数,在继承他的子类当中都要重写这个函数
virtual const char* what()const throw();