抛出异常,捕获

#include <iostream>

using namespace std;

class Myarray
{
protected:
	int m_len;
	int *m_data;
public:
	int &operator [](int index);
	
	Myarray(int l);
	~Myarray();
	int GetLength()
	{
		return m_len;
	}
	class eSize
	{
	public:
		virtual void print()=0;
	};
	class eNegative
	{
	public:
		void print()
		{
			cout<<"eNegative"<<endl;
		}
	};
	class eTooBig
	{
	public:
		void print()
		{
			cout<<"eTooBig"<<endl;
		}
	};
	class eTooSmall
	{
	public:
		void print()
		{
			cout<<"eTooSmall"<<endl;
		}
	};
	class eZero
	{
	public:
		void print()
		{
			cout<<"eZero"<<endl;
		}
	};
};

int &Myarray::operator [](int index)
{
	return m_data[index];
}

Myarray::Myarray(int l)
{
	m_len=l;
	if(m_len<0)
	{
		throw eNegative();
	}
	if(m_len>1000)
	{
		throw eTooBig();
	}
	if(m_len==0)
	{
		throw eZero();
	}
	if(m_len>0&&m_len<10)
	{
		throw eTooSmall();
	}
	m_data=new int[m_len];
}

Myarray::~Myarray()
{
	if(m_data!=NULL)
	{
		delete []m_data;
	}
}

int main()
{
	try
	{
		Myarray a(0);
		
		for(int i=0;i<a.GetLength();i++)
		{
			a[i]=i;
		}
	}
	catch(Myarray::eNegative &e)
	{
		e.print();
	}
	catch(Myarray::eTooBig &e)
	{
		e.print();
	}
	catch(Myarray::eTooSmall &e)
	{
		e.print();
	}
	catch(Myarray::eZero &e)
	{
		e.print();
	}
	return 0;
}

运行结果:

猜你喜欢

转载自blog.csdn.net/ShiHongYu_/article/details/81394545
今日推荐