C++异常层次结构

时间:2022-05-21 12:01:27
 #define _CRT_SECURE_NO_WARNINGS
#include <iostream> using namespace std; class MyArray
{
public:
MyArray(int len);
~MyArray(); public:
int & operator[](int index);
int getlen(); public:
class eSize
{
public:
eSize(int len)
{
size = len;
}
virtual void printfErr()
{
cout << "size:" << size <<endl;
}
protected:
int size;
private:
}; class eNegative : public eSize
{
public:
eNegative(int size):eSize(size)
{
;
}
virtual void printfErr()
{
cout << "eNegative 异常 size:" << size << endl;
}
protected:
private:
};
class eZero : public eSize
{
public:
eZero(int size):eSize(size)
{
;
}
virtual void printfErr()
{
cout << "eZero 异常 size:" << size << endl;
}
protected:
private:
};
class eTooBig : public eSize
{
public:
eTooBig(int size):eSize(size)
{
;
}
virtual void printfErr()
{
cout << "eTooBig 异常 size:" << size << endl;
}
protected:
private:
};
class eTooSmall : public eSize
{
public:
eTooSmall(int size):eSize(size)
{
;
}
virtual void printfErr()
{
cout << "eTooSmall 异常 size:" << size << endl;
}
protected:
private:
}; protected:
private:
int *m_space;
int m_len;
}; MyArray::MyArray(int len)
{
if (len < )
{
throw eNegative(len);
}
else if (len == )
{
throw eZero(len);
}
else if (len > )
{
throw eTooBig(len);
}
else if (len < )
{
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 = ;
} }
int& MyArray::operator[](int index)
{
return m_space[index];
}
int MyArray::getlen()
{
return m_len;
} int main(void)
{
try
{
MyArray a();
for (int i=; i<a.getlen(); i++)
{
a[i] = i+;
printf("%d ", a[i]);
}
}
catch (MyArray::eSize& e)
{
e.printfErr();
} catch (...)
{
;
} cout << "Hello World!" << endl;
system("pause");
return ;
}