Array异常处理

设计一个数组类MyArray,重载【】操作,数组初始化时,对数组的个数进行有效检查。

1、index<0 抛出异常eNegative

2、index=0抛出异常eZero

3、index>1000抛出异常eTooBig

4、index<10抛出异常eTooSmall

5、eSize类是以上类的父类,实现有参数构造、并定义virtual void printfErr()输出错误。

具体实现如下述代码:

#include<iostream>
using namespace std;
class MyArray            //创建一个MyArray类
{
private:
	int m_len;
	int *m_data;
public:
	MyArray(int l);     //写一个含参的构造函数
	~MyArray();
	int &operator [](int index)        //对[]进行重载
	{
		return m_data[index];
	}
	int GetLength()
	{
		return m_len;
	}
	class eSize          //eSize作为其他异常类的父类
	{
	protected:
		const char *Errmsg;
	public:
		eSize(char *msg):Errmsg(msg)
		{}
		void printErr()
		{
			cout << Errmsg << endl;
		}
	};
	class eNegative : public eSize     //eNegative继承于父类eSize  类中类
	{
	public:
		eNegative():eSize("eNegative Exception")
		{}
		void printErr()
		{
			cout << Errmsg << endl;
		}
	};
	class eZero : public eSize
	{
	public:
		eZero():eSize("eZero Exception")
		{}
		void printErr()
		{
			cout << Errmsg << endl;
		}
	};
	class eTooSmall : public eSize
	{
	public:
		eTooSmall():eSize("eTooSmall Exception")
		{}
		void printErr()
		{
			cout << Errmsg << endl;
		}
	};
	class eTOoBig : public eSize
	{
	public:
		eTOoBig():eSize("eTooBig Exception")
		{}
		void printErr()
		{
			cout << Errmsg << endl;
		}
	};
};
MyArray::MyArray(int l)          //构造函数
{
	m_len=l;
	if(m_len<0)                 //根据题目,抛出数组长度异常
	{
		throw eNegative();
	}
	else if(m_len==0)
	{
		throw eZero();
	}
	else if(m_len>0&&m_len<=10)
	{
		throw eTooSmall();
	}
	else if(m_len>1000)
	{
		throw eTooBig();
	}
	m_data=new int[m_len];
}
MyArray::~MyArray()
{
	if(m_data!=NULL)
	{
		delete [] m_data;
	}
}
int main()
{
	try
	{
		MyArray a(30);
		for(int i=0;i<a.GetLength();i++)
		{
			a[i]=i;
		}
	}
	catch(MyArray::eNegative &e)             //捕获异常
	{
		cout << "eNegative Exception" << endl;
	}
	catch(MyArray::eZero &e)
	{
		cout << "eZero Exception" << endl;
	}
	catch(MyArray::eTOoBig &e)
	{
		cout << "eTOoBig Exception" << endl;
	}
	catch(MyArray::eTooSmall &e)
	{
		cout << "eTooSmall Exception" << endl;
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值