函數級的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

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