【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()。
具体异常处理代码如下:
有什么问题希望大家可以指出,谢谢大家~
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; } }
有什么问题希望大家可以指出,谢谢大家~
相关文章推荐
- chapter16test2
- C++拷贝构造函数详解
- ubuntu下用Eclipse完成C语言编程练习
- C++的深拷贝与浅拷贝
- 跳跃表(Skip List)的实现及测试 C++实现
- chapter16test1
- C++中关于输入输出流中c_str
- 黑马程序员——C语言之选择排序、折半查找法与二维数组
- C++ Virtual详解
- 最常用的两种C++序列化方案的使用心得(protobuf和boost serialization)
- 八大排序算法的C++实现
- C++类型转换关键字 *_cast<type> (expression)
- C++类的所占空间
- C++11中std:bind()与SOCKET bind()冲突问题
- Heat
- C++播放wav音乐和音效
- [C语言]进阶|结构类型: 枚举, 结构, 类型定义
- C++ Primer快速入门之三:几种常见的控制语句
- C++对象内存布局 (二)
- [leetcode]Maximum Subarray (C语言)