码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-07-06 12:25:24      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:c++   异常处理   

异常处理的机制:

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;
	}
}

有什么问题希望大家可以指出,谢谢大家~

版权声明:本文为博主原创文章,未经博主允许不得转载。

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

标签:c++   异常处理   

原文地址:http://blog.csdn.net/qaz3171210/article/details/46771307

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!