继承中的异常处理
#include<iostream>
using namespace std;
//原始方法
class Arrary
{
public:
Arrary(int);
~Arrary();
int &operator[](int dex);
int getlen();
class Size
{};
class SizeErro
{};
class SizeZero
{};
class SizeToSmall
{};
class SizeToLarge
{};
public:
int m_len;
int *m_space;
};
Arrary::Arrary(int len)//构造函数没有返回值,通过异常进行处理是常用的手段
{
m_len = len;
m_space = new int[len];
if (len < 0) throw SizeErro();
else if (len = 0) throw SizeZero();
else if (len <= 2) throw SizeToSmall();
else if (len > 100) throw SizeToLarge();
}
Arrary::~Arrary()
{
delete[] m_space;
m_len = 0;
m_space = NULL;
}
int Arrary::getlen()
{
return m_len;
}
int &Arrary::operator[](int dex)
{
return m_space[dex];
}
void main()
{
try
{
Arrary a(1);
for (int i = 0; i < a.getlen();i++)
{
a[i] = i + 1;
cout << a[i] << endl;
}
}
catch (Arrary::SizeToSmall e)
{
cout << "SizeToSmall" << endl;
}
catch (...)
{
}
system("pause");
}
使用继承
class Arrary
{
public:
Arrary(int);
~Arrary();
int &operator[](int dex);
int getlen();
class Size
{
public:
virtual string printSize()
{
return "Size";
}
};
class SizeErro:public Size
{
virtual string printSize()
{
return "SizeErro";
}
};
class SizeZero :public Size
{
virtual string printSize()
{
return "SizeZero";
}
};
class SizeToSmall :public Size
{
virtual string printSize()
{
return "SizeToSmall";
}
};
class SizeToLarge :public Size
{
virtual string printSize()
{
return "SizeToLarge";
}
};
public:
int m_len;
int *m_space;
};
Arrary::Arrary(int len)//构造函数没有返回值,通过异常进行处理是常用的手段
{
m_len = len;
m_space = new int[len];
if (len < 0) throw SizeErro();
else if (len = 0) throw SizeZero();
else if (len <= 2) throw SizeToSmall();
else if (len > 100) throw SizeToLarge();
}
Arrary::~Arrary()
{
delete[] m_space;
m_len = 0;
m_space = NULL;
}
int Arrary::getlen()
{
return m_len;
}
int &Arrary::operator[](int dex)
{
return m_space[dex];
}
void main()
{
try
{
Arrary a(1);
for (int i = 0; i < a.getlen();i++)
{
a[i] = i + 1;
// cout << a[i] << endl;
}
}
catch (Arrary::Size &e)
{
cout << "Size" <<e.printSize()<< endl;
}
catch (...)
{
cout << "未知类型" << endl;
}
system("pause");
}