#include <iostream>
using namespace std;
template <typename Type>
class PushOnStackFull//异常类的定义
{
private:
Type value;
string str;
public:
PushOnStackFull(const char* s,int val):str(s),value(val){}
~PushOnStackFull(){}
public:
void what()const//出现异常弹出的提示
{
cout << str <<endl;
cout << value << " can not push stack" <<endl;
}
};
template <typename Type>
class Stack
{
private:
int capacity;
int top;
Type *idata;
enum
{
STACK_SIZE = 8 //设置堆栈的最小数据结构
};
public:
Stack(int size = STACK_SIZE);
~Stack();
public:
bool Push(const Type &data);
bool Pop(void);
bool IsFull();
bool IsEmpty();
void Show() const;
};
template <typename Type>
void Stack<Type>::Show() const//遍历栈元素,const方法是防止修改栈内元素
{
for (int i = top - 1; i >= 0; i--)
cout << idata[i] << endl;
}
template <typename Type>
bool Stack<Type>::IsFull()//是否满栈
{
return top >= capacity;
}
template <typename Type>
bool Stack<Type>::IsEmpty()//是否是空栈
{
return top <= 0;
}
template <typename Type>
bool Stack<Type>::Pop(void)//弹出
{
if (IsEmpty())
{
cout << "Stack is empty !" << endl;
return false;
}
else
{
top = top -1;
return true;
}
}
template <typename Type>
bool Stack<Type>::Push(const Type &data)//压栈
{
if (IsFull())
{
throw PushOnStackFull<Type>("Stack full !",data);//系统扔出异常类
}
else
{
idata[top++] = data;
return true;
}
}
template <typename Type>
Stack<Type>::Stack(int size)//初始化
{
capacity = size > STACK_SIZE ? size : STACK_SIZE;
idata = new Type[capacity];
top = 0;
}
template <typename Type>
Stack<Type>::~Stack(/* args */)//析构
{
if (idata != NULL)
delete[] idata;
idata = NULL;
top = 0;
capacity = 0;
}
int main()
{
Stack<int> s(7);
try//测试下面语句
{
for (int i = 0; i < 10; i++)
{
s.Push(i);
}
}
catch(const PushOnStackFull<int>& e)//捕获该语句扔出的异常
{
e.what();//调用相应的的方法
}
s.Show();
return 0;
}
系统异常自带异常类
C++标准库提供的逻辑异常包括:
invalid_argment异常,接收到一个无效的实参,抛出该异常。
out_of_range异常,收到一个不在预期范围中的实参,则抛出。
length_error异常,报告企图产生“长度值超出最大允许值”的对象
domain_error异常,用以报告域错误(domain error)
C++标准库提供的运行时异常包括:
range_error异常,报告内部计算中的范围错误。
overflow_error异常,报告算术溢出错误。
underflow_error异常,报告算术下溢错误。
以上三个异常是由runtime_error类派生的。
bad_alloc异常。当new()操作符不能分配所要求的存储区时,会抛出该异常。它是由基类exception派生的。
#include <iostream>
using namespace std;
template <typename elemtType>
class Array
{
private:
int length;
elemtType *idata;
enum
{
DefaultArraySize = 8
};
public:
explicit Array(int size = DefaultArraySize)
{
length = size > 0 ? size : 0;
idata = new elemtType[length]{1,2,3,4,5,6,7,8};
}
~Array()
{
delete[] idata;
}
elemtType &operator[](int index) const
{ //下标运算符[]重载
if (index >= length || index < 0)
{ //增加异常抛出,防止索引越界
string eObj = "out of range error in Array<elemtType>::elemtType& operator[](int index) const";
throw out_of_range(eObj);//扔出一个异常类,该类是系统库已经定义好的
}
return idata[index];
}
};
int main()
{
int i;
Array<int> arr;
try
{
for (int i = 0; i < 10; i++)
{
cout << arr[i] << " ";
}
}
catch (const out_of_range &e)
{
cerr << e.what() << '\n';
return -1;
}
return 0;
}