在异常处理中处理析构函数
来源:互联网 发布:天津市软件学院答辩 编辑:程序博客网 时间:2024/04/27 22:07
一个例子:
输出结果:
#include<iostream>#include<string>using namespace std;class Student{public:Student(int n,string nam){num=n;name=nam; cout<<"constructor-->"<<num<<endl;}~Student(){cout<<"destructor-->"<<num<<endl; }void get_data();private:int num;string name;};void Student::get_data(){if(num==0)throw num;//当num=0的时候,将int型变量num抛出else cout<<num<<" "<<name<<endl;//当num≠0的时候,输出num和namecout<<"in get_data()"<<endl; //输出信息,表示目前在get_data中 } void fun(){Student stud1(1,"Tan");stud1.get_data();cout<<"\n============分割线呼啸而过======================\n"<<endl; Student stud2(0,"Li");stud2.get_data();} int main(){cout<<"main begin"<<endl;cout<<"call fun()"<<endl;try{fun(); } catch(int n){cout<<"num="<<n<<",error!"<<endl; }cout<<"main end"<<endl;return 0; }
输出结果:
/*main begincall fun()constructor-->11 Tanin get_data()============分割线呼啸而过======================constructor-->0destructor-->0destructor-->1num=0,error!main end*/
分析:函数fun中,当执行到stud2.get_data()的时候,get_data函数抛出异常,因为get_data函数中没够catch结果,所以无法捕捉异常,只能像上级传递,返回到了fun函数中。在fun中也没有catch结构,所以就又返回到了main函数中。因为stud1和stud2实在fun函数中定义的,所以当异常从catch返回到main函数的时候,这两个对象的生命周期已经结束,所以按照“先构造的对象后析构”的原则进行析构,所以输出destructor-->0和destructor->1。然后等到了main函数中,发现有与之匹配的catch函数,所以执行执行异常操作,然后继续执行异常操作之后的语句。
从这个例子还可以看出,我们抛出异常的位置一般位于函数体的首部,在函数体中首先进行检验,发现有异常就立即抛出,因为它继续执行函数体中的接下来的语句是没有意义的。
1 0
- 在异常处理中处理析构函数
- 在异常处理中处理析构函数
- 析构函数中异常处理
- 在单元测试中对异常的处理
- 在B/S开发中处理异常
- 在Java Servlet中处理异常
- 在servlet中,怎么处理系统异常?
- 怎样在loop中处理异常
- 如何在shell中处理异常
- 在MVC中处理异常的总结
- 如何在Application中进行异常处理
- Scanner在异常处理中死循环
- 构造函数/析构函数中的异常处理
- php异常处理函数
- _set_invalid_parameter_handler异常处理函数
- win32异常处理函数
- signal函数异常处理
- _set_invalid_parameter_handler异常处理函数
- SQLServer As
- CString string 的相互转化,宽字符,多字符的转换
- Codeforece#219(DIV2) C题
- Cookie的基础知识
- 20131214-第七天
- 在异常处理中处理析构函数
- ++i和i++效率谁高
- android scrollview 嵌套listview 或者listview嵌套listview 计算子view高度
- Fedora18设置终端快捷键 和 桌面快捷方式
- UltraGrid中绑定UltraTextEditor在AfterEditorButtonCloseUp事件中获得所属UltraGridCell
- 使用管道批量删除deb
- 想要在linux上深入发展可以在两个方面上专研,虚拟内存和进程
- 【SSRS报表】创建第一个SSRS报表
- 应用webview 获取网页事件