C++中的异常栈展开是指,当某个函数中有异常产生(这里不考虑是主动抛出的还是被动产生的),在异常被捕获之前的函数调用链上,函数不会正常执行返回,即异常产生之后的程序逻辑不会被执行。
(注意:这里不从操作系统层面来讨论函数调用栈等相关观念)
看下面一个示例: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" ;B(d, i + 1);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;
}/* Output:Entering mainCreated Dummy: MCopy created Dummy: MEntering FunctionACopy created Dummy: AEntering FunctionBCopy created Dummy: BEntering FunctionCDestroyed Dummy: CDestroyed Dummy: BDestroyed Dummy: ADestroyed Dummy: MCaught an exception of type: class MyExceptionExiting main.
*/
把函数之间的调用关系用图表示,如下所示: