C++沒有final或finally,如何解決異常情況下資源的釋放問題?

#include "stdafx.h"
#include <iostream>

class TestA
{
public:
	TestA()
	{
		std::cout << "TestA" << std::endl;
	}

	~TestA()
	{
		std::cout << "~TestA" << std::endl;
	}

	void Print()
	{
		int a = 20;
		int b = 1;

		std::cin >> b;
		std::cout << "a / b = " << a / b << std::endl;
	}
};


int main()
{
	try
	{
		TestA a;
		a.Print();
	}
	catch (std::exception& e)
	{
		std::cerr << e.what() << std::endl;
	}
	catch (...)
	{
		std::cout << "Unknown Exception" << std::endl;
	}

	int b = 0;
	std::cin >> b;

    return 0;
}

以上代碼運行時,如果輸入0,就會產生異常!然而C++並沒有final或finally這樣的方式來對異常發生後的處理。這個時候就需要用到析構函數,運行程序,輸入0,最後打印:

TestA
0
~TestA
Unknown Exception

當拋出異常後,TestA對象的析構函數先於異常捕獲被調用,且一定能被調用!

要捕獲SEH異常,請參考:C++使用try,catch在VS2015中捕獲異常

 

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