1. 程式人生 > >C++沒有final或finally,如何解決異常情況下資源的釋放問題?

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中捕獲異常