解析C++编程中异常相关的堆栈展开和throw()异常规范
C++ 中的异常和堆栈展开 #include <string> #include <iostream> using namespace std; class MyException{}; class Dummy { public: Dummy(string s) : MyName(s) { PrintMsg("Created Dummy:"); } Dummy(const Dummy& other) : MyName(other.MyName){ PrintMsg("Copy created Dummy:"); } ~Dummy(){ PrintMsg("Destroyed Dummy:"); } void PrintMsg(string s) { cout << s << MyName << endl; } string MyName; int level; }; void C(Dummy d,int i) { cout << "Entering FunctionC" << endl; d.MyName = " C"; throw MyException(); cout << "Exiting FunctionC" << endl; } void B(Dummy d,int i) { cout << "Entering FunctionB" << endl; d.MyName = "B"; C(d,i + 1); cout << "Exiting FunctionB" << endl; } void A(Dummy d,int i) { cout << "Entering FunctionA" << endl; d.MyName = " A" ; // Dummy* pd = new Dummy("new Dummy"); //Not exception safe!!! B(d,i + 1); // delete pd; cout << "Exiting FunctionA" << endl; } int main() { cout << "Entering main" << endl; try { Dummy d(" M"); A(d,1); } catch (MyException& e) { cout << "Caught an exception of type: " << typeid(e).name() << endl; } cout << "Exiting main." << endl; char c; cin >> c; }输出: Entering main Created Dummy: M Copy created Dummy: M Entering FunctionA Copy created Dummy: A Entering FunctionB Copy created Dummy: B Entering FunctionC Destroyed Dummy: C Destroyed Dummy: B Destroyed Dummy: A Destroyed Dummy: M Caught an exception of type: class MyException Exiting main.
异常规范 (throw)
void MyFunction(int i) throw(); 告诉编译器函数不引发任何异常。它相当于使用 __declspec(nothrow)。这种用法是可选的。
如果在应用程序中使用异常处理,则一定有一个或多个函数处理引发的异常。在引发异常的函数和处理异常的函数间调用的所有函数必须能够引发异常。
不允许对 C 函数使用显式异常规范。 下表总结了函数的引发行为: // exception_specification.cpp // compile with: /EHs #include <stdio.h> void handler() { printf_s("in handlern"); } void f1(void) throw(int) { printf_s("About to throw 1n"); if (1) throw 1; } void f5(void) throw() { try { f1(); } catch(...) { handler(); } } // invalid,doesn't handle the int exception thrown from f1() // void f3(void) throw() { // f1(); // } void __declspec(nothrow) f2(void) { try { f1(); } catch(int) { handler(); } } // only valid if compiled without /EHc // /EHc means assume extern "C" functions don't throw exceptions extern "C" void f4(void); void f4(void) { f1(); } int main() { f2(); try { f4(); } catch(...) { printf_s("Caught exception from f4n"); } f5(); } 输出: About to throw 1 in handler About to throw 1 Caught exception from f4 About to throw 1 in handler (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |