分类: C/C++
2014-02-28 11:29:21
以下示例演示引发异常时,该堆栈如何展开。 C to the catch statement in main, and unwinds each function along the way." xml:space="preserve" style="margin:0px;padding:0px;border:0px;outline:0px;background-color:transparent;">在线程的执行与在C的 throw 语句中跳转到maincatch 语句,并展开每个功能。 Dummy objects are created and then destroyed as they go out of scope." xml:space="preserve" style="margin:0px;padding:0px;border:0px;outline:0px;background-color:transparent;">请注意Dummy对象被创建并被销毁的顺序,但超出范围。 main, which contains the catch statement." xml:space="preserve" style="margin:0px;padding:0px;border:0px;outline:0px;background-color:transparent;">和函数未完成除main,包含 catch 语句的通知。 A never returns from its call to B(), and B never returns from its call to C()." xml:space="preserve" style="margin:0px;padding:0px;border:0px;outline:0px;background-color:transparent;">功能A从其从不返回对B(),并且,B从其从不返回对C()。 Dummy pointer and the corresponding delete statement, and then run the program, notice that the pointer is never deleted." xml:space="preserve" style="margin:0px;padding:0px;border:0px;outline:0px;background-color:transparent;">如果取消注释Dummy指针的定义和对应 delete 语句,然后运行程序,请注意指针不会删除。 这将显示可能发生的问题,当函数不提供一个异常确保时。 有关更多信息,请参见如何:设计异常。 如果批注 catch 语句,可以观察发生了什么由于未经处理的异常,那么,当程序终止。
#include#include 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; } /* Output: 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. */