异常层次结构

#include <iostream>

using namespace std;

const int DefaultSize = 10;

// 动态数组,
class Array
{
public:
	Array(int itsSize = DefaultSize);
	~Array() { delete [] pType; }

	// 运算符重载,
	int& operator[] (int offSet); // offSet 是代表下标的数,
	const int& operator[] (int offSet) const;

	// 访问器,accessors
	int GetitsSize() const { return itsSize; }
	// 异常类。
	class xBoundary{};
	class xSize
	{
	public:
		xSize(){}
		xSize(int size) : itsSize(size) {}
		~xSize(){}
		int GetSize() { return itsSize; }
		virtual void PrintError()   // 这是虚函数,
		{
			cout << "下标发生错误:" << itsSize << endl;
		}
	protected:
		int itsSize;
	};
	class xZero : public xSize
	{
	public:
		xZero(int size) : xSize(size){}
		virtual void PrintError()
		{
			cout << "下标不能是0."<< endl;
		}
	};
	class xNegative : public xSize
	{
	public:
		xNegative(int size):xSize(size){}
		virtual void PrintError()
		{
			cout << "下标不能是负的."<< endl;
		}
	};
	class xTooSmall : public xSize
	{
	public:
		xTooSmall(int size) :xSize(size){}
		virtual void PrintError()
		{
			cout << "下标不能是小于10."<< endl;
		}
	};
	class xTooBig : public xSize
	{
	public:
		xTooBig(int size) :xSize(size){}
		virtual void PrintError()
		{
			cout << "下标不能大于50000."<< endl;
		}
	};
private:
	int *pType;
	int itsSize;

};

int& Array::operator[](int offSet)
{
	int size = this->GetitsSize();
	if(offSet >= 0 && offSet < size)
		return pType[offSet];
	throw xBoundary();
}

const int& Array::operator [](int offSet) const
{
	int size = this->GetitsSize();
	if(offSet >= 0 && offSet < size)
		return pType[offSet];
	throw xBoundary();
}

Array::Array(int size) : itsSize(size)
{
	if(size == 0)
		throw xZero(size);
	else if(size < 0)
		throw xNegative(size);
	else if(size < 10)
		throw xTooSmall(size);
	else if(size > 90000)
		throw xTooBig(size);
	

	pType = new int[size];
	for(int i = 0; i < size; i++)
		pType[i] = 0;

}

int main()
{
	try
	{
		Array a;
	    /*Array b(12);*/
	    Array intArray(20);
		Array b(2);
	   /*b[4] = 20;
	   b[20] = 50;
	   cout << b[4] << endl;*/
		for(int j = 0; j < 100; j++)
		{
			intArray[j] = j;
			cout << "intArray[" << j << "]  ok...." << endl;
		}
	}
	
	catch(Array::xBoundary)
	{
		cout << "下标越界了," << endl;
	}
	catch(Array::xSize& exp)
	{
		exp.PrintError();   // 这是一个多态性,是一个虚函数,
	}
	/*catch(Array::xZero theException)
	{
		cout << "下标不能小于0, " << endl;
	}
	catch(Array::xNegative theException)
	{
		cout << "下标不能小于0," << theException.GetSize() << endl;
	}
	catch(Array::xTooSmall theException)
	{
		cout << "下标不能小于10, " << theException.GetSize() << endl;
	}
	catch(Array::xTooBig theException)
	{
		cout << "下标不能大于90000," << theException.GetSize() << endl;
	}*/
	
	catch(...) // 这个是捕获剩余的其它的异常,
	{
		cout << "发生未知异常?" << endl;
	}

	cout << "Done. " << endl;

	return 0;
}

你可能感兴趣的:(异常层次结构)