📄 demo_exception_handling_7_a.cpp
字号:
//****************************************************
// 在异常处理中的析构函数
//****************************************************
# include <iostream>
# include <string>
using namespace std;
class Student
{
public:
Student(int n,string nam) //构造函数
{
cout<<"constructor - "<<n<<endl;
num=n;
name=nam;
}
~Student() //析构函数
{
cout<<"destructor - "<<num<<endl;
}
void get_data();
private:
int num;
string name;
};
void Student::get_data()
{
cout<<"begin of get_data()"<<endl;
if(num==0)
{
cout<<"begin of throw exception"<<endl;
throw num; //抛出int型异常后程序控制转向类型匹配的catch处理块
cout<<"end of throw exception"<<endl;
}
else
cout<<num<<" : "<<name<<endl;
cout<<"end of get_data()"<<endl;
}
void fun()
{
Student stud1(1101,"Tan");
stud1.get_data();
Student stud2(0,"Li");
stud2.get_data();
}
int main()
{
cout<<"begin of main()"<<endl;
cout<<"call fun()"<<endl;
try //测试异常
{
fun();
}
catch(int n) //throw抛出的异常被catch捕获,形参初始化后析构try开始点到throw点构造的对象
{
cout<<"begin of catch exception"<<endl;
cout<<"num="<<n<<", error!"<<endl;
cout<<"end of catch exception"<<endl;
}
cout<<"end of main()"<<endl;
return 0;
}
/*
begin of main()
call fun()
constructor - 1101
begin of get_data()
1101 : Tan
end of get_data()
constructor - 0
begin of get_data()
begin of throw exception
destructor - 0
destructor - 1101
begin of catch exception
num=0, error!
end of catch exception
end of main()
*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -