-
抛出自定义类型的类也可以当作异常类(自己写的异常描述类),专门用来描述程序出现的问题
-
写一个类继承标准库中的异常类去描述异常
自己写的异常描述类 - - - 一般在综合管理错误的处理时使用,可能同一个问题在程序中出现多次
class Error
{
public:
Error(const char* str = "未知错误") :str(str) {}
const char* what()const
{
return str.c_str();
}
protected:
string str;
};
void insertArray(int array[], int* curNum, int posData, int maxLength)
{
if (*curNum >= maxLength)
{
throw Error("数组下标溢出!");
}
array[*curNum] = posData;
(*curNum)++;
}
void testOne()
{
try
{
int array[3] = { 0,0,0 };
int curNum = 0;
for (int i = 0; i < 4; i++)
{
insertArray(array, &curNum, i, 3);
}
}
catch (Error str)
{
cout << str.what() << endl;
}
}
int main()
{
testOne();
return 0;
}
/*输出*/
数组下标溢出!
继承标准库中的异常类 - - - 通过重写what()方法,不需要自己定义数据成员,只需要传参即可
class myException :public exception //自己的异常类继承标准库中的异常类
{
public: //父类中为char*类型,把string转换为char*
myException(string str) :exception(str.c_str()) {}
};
void insertArray(int a) //数组插入
{
if (a >= 4)
throw myException("数组满了!");
cout << "插入成功" << endl;
}
void deleteArray(int a)
{
if (a <= 0)
throw myException("数组为空,无法删除!");
cout << "删除成功" << endl;
}
void testTwo()
{
try //插入的异常捕获
{
insertArray(1);
insertArray(4); //存在异常
}
catch (myException& object)
{
cout << object.what() << endl;
}
try //删除的异常捕获
{
deleteArray(1);
deleteArray(0); //存在异常
}
catch (myException& object)
{
cout << object.what() << endl; //what()方法是继承标准库中的
}
}
int main()
{
testTwo();
return 0;
}
/*输出*/
插入成功
数组满了!
删除成功
数组为空,无法删除!