#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,最後打印:ios
TestA 0 ~TestA Unknown Exception
當拋出異常後,TestA對象的析構函數先於異常捕獲被調用,且必定能被調用!函數
要捕獲SEH異常,請參考:C++使用try,catch在VS2015中捕獲異常.net