您的位置:首页 > 编程语言 > C语言/C++

【C++】栈空栈满异常处理

2015-07-06 10:13 706 查看
异常处理的机制:

1.如果没有异常发生,继续执行try块中的代码,与try块相关联 的catch子句被忽略,程序正常执行,main()返回0。

2.当第一个try块在for循环中抛出异常,则该for循环退出,try块也退出,去执行pushOnFull异常的catch子句。istack.PrintStack()不再执行,被忽略。

3.如果第二个try块调用Pop()抛出异常,则退出for和try块,去执行popOnEmpty异常的catch子句。

4.当某条语句抛出异常时,跟在该语句后面的语句将被跳过。程序执行权交给处理异常的catch子句,如果没有catch子句能够处理异常,则交给C++标准库中定义的terminate()。

具体异常处理代码如下:

#include<iostream>
#include<iomanip>
#include<string>
using namespace std;

//异常类
template<class Type>
class PushOnFull                    //栈满异常
{
public:
PushOnFull(string s):str(s)
{}
Type GetData()const
{
return data;
}
string what()                   //输出提示语句
{
return str;
}
bool ReMalloc()
{
return true;
}
private:
string str;
};

template<class Type>
class PopOnEmpty                     //栈空异常
{
public:
PopOnEmpty(string s):str(s)
{}
string what()const               //输出提示语句
{
return str;
}
private:
string str;
};

template<class Type>
class Stack                           //栈
{
public:
Stack(int sz=SIZE)
{
capacity = sz>SIZE?sz:SIZE;
base = new Type[capacity];
top = 0;
}
~Stack()
{
delete []base;
base = NULL;
}
public:
bool IsFull()const                    //判断是否为满
{
return top >= capacity;
}
bool IsEmpty()const                   //判断是否为空
{
return top == 0;
}
void Push(const Type &x)              //入栈
{
if(IsFull())
{
string str("栈满入栈异常发生!");
throw PushOnFull<Type>(str);  //抛出异常
}
base[top++] = x;
}
void Pop()                            //出栈
{
if(IsEmpty())
{
string str = "发生栈空出栈异常!";
throw PopOnEmpty<Type>(str);  //抛出异常
}
top--;
}

private:
enum{SIZE=8};
Type *base;
size_t capacity;
int    top;
};

void main()
{
Stack<int> st;
try                                    //异常处理
{
for(int i=1; i<=5; ++i)
{
st.Push(i);
}
}
catch(PushOnFull<int> &e)              //捕获异常
{
cout<<e.what()<<endl;
}

try                                   //异常处理
{
for(int i=0; i<10; ++i)
{
st.Pop();
}
}
catch(PopOnEmpty<int> &exp)           //捕获异常
{
cout<<exp.what()<<endl;
}
}


有什么问题希望大家可以指出,谢谢大家~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: