在程序运行时,可能由于某些隐藏的bug突然爆发而导致程序崩溃,,而这些隐藏的bug调试起来非常麻烦,所以,C++提供了一种异常捕捉抛出机制,在有可能有隐患的代码块前加try关键字,后面再使用catch关键字捕捉异常,如果捕捉到,可以在catch代码块中使用throw关键字抛出异常。
程序要求:设计一个数组类MyArray,重载[ ]操作,数组初始化时,对数组的个数进行有效的检查:
1. index < 0 抛出异常eNegative;
2. index = 0 抛出异常eZero;
3. index > 1000 抛出异常eTooBig;
4. index <10 抛出异常eTooSmall;
5. eSise 类是以上类的父类,实现有参数构造,并定义 virtual void printErr( ) 输出错误。
参考程序:
#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)
{
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")
{
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")
{
}
const char *GetE()
{
return ErrMsg;
}
};
class eTooSmall : public Error
{
public:
eTooSmall() : Error("eTooSmall")
{
const char *GetE()
{
return ErrMsg;
}
};
class eZero : public Error
{
public:
eZero() : Error("eZero")
{
}
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();
};
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];
}
{
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;
}
}
{
if(data!=NULL)
{
delete data;
data = NULL;
}
}
int &Array::operator [](int index)
{
return data[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;
}