自定义异常类

#include <iostream>
using namespace std;

class MyArray
{
public:
	MyArray(int size);
	~MyArray();
public:
	int & operator[](int index);
	int getLen();
	/*
	1) 抛出异常eNegative  
	2)index = 0 抛出异常 eZero  
	3)index>1000抛出异常eTooBig 
	4)index<10 抛出异常eTooSmall 
	5)eSize类是以上类的父类,*/
	class eSize
	{
	public:
		eSize(int size)
		{
			m_size = size;
		}
		virtual void printS()
		{
			cout<<"eSize::size:"<<m_size<<endl;
		}
	protected:
		int m_size;
	};
	class eNegative:public eSize
	{
	public:
		eNegative(int size):eSize(size)
		{
			cout<<"eNegative"<<endl;
		}
		void printS()
		{
			cout<<"eNegative::size:"<<m_size<<endl;
		}
	};
	class eZero:public eSize
	{
	public:
		eZero(int size):eSize(size)
		{
			cout<<"eZero"<<endl;
		}
		void printS()
		{
			cout<<"eZero::size:"<<m_size<<endl;
		}

	};
	class eTooBig:public eSize
	{
	public:
		eTooBig(int size):eSize(size)
		{
			cout<<"eTooBig"<<endl;
		}
		void printS()
		{
			cout<<"eTooBig::size:"<<m_size<<endl;
		}
	};
	class eTooSmall:public eSize
	{
	public:
		eTooSmall(int size):eSize(size)
		{
			cout<<"eTooSmall"<<endl;
		}
		void printS()
		{
			cout<<"eTooSmall::size:"<<m_size<<endl;
		}
	};
	
protected:
private:
	int *m_space;
	int m_size;
};

MyArray::MyArray(int size)
{
	if (size<0)
	{
		throw eNegative(size);
	} 
	else if(size==0)
	{
		throw eZero(size);
	}
	else if (size>1000)
	{
		throw eTooBig(size);
	}
	else if(size<3)
	{
		throw eTooSmall(size);
	}
	m_space = new int[size];
	m_size = size;
}
MyArray::~MyArray()
{
	if (m_space!=NULL)
	{
		delete[] m_space;
		m_size = 0;
	}
}
int & MyArray::operator[](int index)
{
	return m_space[index];
}
int MyArray::getLen()
{
	return m_size;
}
int main()
{
	try
	{
		MyArray a(2);
		for (int i =0;i<a.getLen();i++)
		{
			a[i] = i+1;
			printf("a:%d\n",a[i]);
		}
	}
	catch (MyArray::eSize &e)
	{
		e.printS();
		//cout<<e.<<endl;
	}
	catch (...)
	{
		cout<<"未知异常"<<endl;
	}
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值