C++异常处理 --- 自定义异常类

  • 抛出自定义类型的类也可以当作异常类(自己写的异常描述类),专门用来描述程序出现的问题

  • 写一个类继承标准库中的异常类去描述异常 

自己写的异常描述类 - - - 一般在综合管理错误的处理时使用,可能同一个问题在程序中出现多次

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;
}

/*输出*/
插入成功
数组满了!
删除成功
数组为空,无法删除!
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qiuqiuyaq

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值