c++异常处理机制与栈展开的理解

142 阅读1分钟

直接上代码:

// 函数f1会抛出一个异常
void f1()
{
    cout << "f1() Start\n";
    throw 100;
    cout << "f1() End\n";
}
 
// 调用函数f1
void f2(){
    cout<<"f2() Start\n";
    try {
        f1();
    } catch(int i) { 
        cout << "first catch process" << std::endl;
    }
    cout << "f2() End\n";
}
  
// 调用函数f2,并处理f1()抛上来的异常
void f3() {
    cout << "f3() Start\n";
    try {
        f2();
    } catch(int i) {
        cout<<"Caught Exception: " << i << std::endl;
    }
    cout<<"f3() End\n";
}
 
// 演示栈展开过程的程序
int main()
{
    f3();
    return 0;
}

输出结果为:
f3() Start
f2() Start
f1() Start
first catch process
f2() End
f3() End

也就是说异常处理走到第一个catch就不再继续寻找下一个catch了,因此f3()中的catch不会触发。
如果把f2()中的catch去掉,改为:

void f2(){
    cout<<"f2() Start\n";
    f1();
    cout << "f2() End\n";
}

则执行结果为:
f3() Start
f2() Start
f1() Start
Caught Exception: 100
f3() End
也就是说,从异常引发的f1()函数一直向上找,直到找到第一个catch,也就是f3()里的catch为止。如果一直没有找到catch,则会触发程序的terminate,直接挂掉。