异常的层次结构

#include<iostream>
using namespace std;

class MyArray
{
public:
	MyArray(int len);
	~MyArray();
public:
	int &operator[](int index);
	int getLen();

	class eSize
	{
	public:
		eSize(int size)
		{
			m_size = size;
		}
		virtual void printErr()
		{
			cout << "size:" << m_size << " ";
		}
	protected:
		int m_size;
	};
	class eNegative:public eSize
	{
	public:
		eNegative(int size) :eSize(size)
		{

		}
		virtual void printErr()
		{
			cout << " eNegative size:" << m_size << " ";
		}
	};
	class eZero :public eSize
	{
	public:
		eZero(int size) :eSize(size)
		{

		}
		virtual void printErr()
		{
			cout << " eZero size:" << m_size << " ";
		}
	};
	class eTooBig :public eSize
	{
	public:
		eTooBig(int size) :eSize(size)
		{

		}
		virtual void printErr()
		{
			cout << "eTooBig size:" << m_size << " ";
		}
	};
	class eTooSmall :public eSize	
	{
	public:
		eTooSmall(int size) :eSize(size)
		{

		}
		virtual void printErr()
		{
			cout << "eTooSmall size:" << m_size << " ";
		}
	};
private:
	int *m_space;
	int m_len;
};

MyArray::MyArray(int len)
{
	if (len < 0)
	{
		throw eNegative(len);
	}

	if (len =0)
	{
		throw eZero(len);
	}

	if (len >1000)
	{
		throw eTooBig(len);
	}

	if (len < 10)
	{
		throw eTooSmall(len);
	}

	m_len = len;
	m_space = new int[len];
}

MyArray::~MyArray()
{
	if (m_space != NULL)
	{
		delete m_space;
		m_space = NULL;
		m_len = 0;
	}
}

int &MyArray::operator[](int index)
{
	return m_space[index];
}

int MyArray::getLen()
{
	return m_len;
}

void main()
{
	try
	{
		MyArray a(-5);
		for (int i = 0; i < a.getLen(); i++)
		{
			a[i] = i + 1;
			printf("%d ", a[i]);
		}
	}
	catch (MyArray::eSize &e)
	{
		e.printErr();
	}
	catch (...)
	{
		cout << "其他异常!" << endl;
	}

}

void main51()
{
	try
	{
		MyArray a(-5);
		for (int i = 0; i < a.getLen(); i++)
		{
			a[i] = i + 1;
			printf("%d ", a[i]);
		}
	}

	catch (MyArray::eNegative e)
	{
		cout << "eNegative类型异常!" << endl;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值