函数级的try块

参考《Thinking in c++》函数级的try块。

(1)基类抛出异常,子类捕获异常,再抛出异常

#include <iostream>
using namespace std;

class Base {
	int i;
public:
	class BaseExcept{};
	Base(int i):i(i)
	{
		throw BaseExcept();
	}	
};

class Derived : public Base {
public:
	class DerivedExcept
	{
		const char* msg;
	public:
		DerivedExcept(const char* msg):msg(msg){}
		const char * what() const{return msg;}
	};
	Derived(int j)try: Base(j)
	{
		cout<<"this won't print"<<endl;
	}catch(BaseExcept&)
	{
		throw DerivedExcept("base subobject threw");
	}
};

int main() {
	try {
		Derived d(3);
	} catch(Derived::DerivedExcept&de) {
		cout<<de.what()<<endl;
	}
	return 0;
}

 

输出:base subobject threw

(2)当子类捕获基类异常后不做处理,主函数main在调用子类时,可以捕获基类异常

#include <iostream>
using namespace std;

class Base {
	int i;
public:
	class BaseExcept
	{
	public:
		void test() const{
			cout<<"this is a test"<<endl;
		}
	};
	Base(int i):i(i)
	{
		throw BaseExcept();
	}	
};

class Derived : public Base {
public:
	class DerivedExcept
	{
		const char* msg;
	public:
		DerivedExcept(const char* msg):msg(msg){}
		const char * what() const{return msg;}
	};
	Derived(int j)try: Base(j)
	{
		cout<<"this won't print"<<endl;
	}catch(BaseExcept&)
	{
		//子类不做任何处理
	}
};

int main() {
	try {
		Derived d(3);
	} catch(Base::BaseExcept&de) {
		de.test();//可以捕获基类的异常
	}
	return 0;
}

输出:this is a test

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章