⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 demo_exception_handling_7_b.cpp

📁 对于一个初涉VC++的人来书
💻 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()
{
	cout<<"begin of fun()"<<endl;

	Student stud1(1101,"tan");
	stud1.get_data();

	try
	{
		Student stud2(0,"Li");
		stud2.get_data();
	}

	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 fun()"<<endl;
}

int main()
{
	cout<<"begin of main()"<<endl;

	cout<<"call fun()"<<endl;
	fun();

	cout<<"end of main()"<<endl;
	
	return 0;
}

/*
begin of main()
call fun()
begin of 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
begin of catch exception
num=0, error!
end of catch exception
end of fun()
destructor - 1101
end of main()
*/

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -