C++中的rethrowing 異常重新拋出

首先解釋一下爲什麼要重新拋出異常,在C++ Primer中是這麼解釋的:有時,單個catch不能完全處理一個異常,在進行了一些校正操作之後,當前的catch可能會決定由調用鏈更上一層的函數來接着處理異常。

其實說白了,也就是異常的值會不停發生變化,需要層層處理。

第一種是通過函數傳遞異常的調用,注意:一定要傳遞異常的引用!

#include <iostream>
#include <exception>

using namespace std;
struct match_error:public logic_error{
    int a,b;
    match_error(int a1,int b1):logic_error("error"),a(a1),b(b1){}
};
void f(int a,int b){
    try{
        throw match_error(a,b);
    }catch(match_error&e){
        cout<<"first match"<<endl;
        throw;
    }
}
void func(int a,int b){
    try{
        f(a,b);
    }catch(match_error &e){
        cout<<"second error"<<endl;
    }

}



int main() {
    func(1,1);
    return 0;
}

第二種

#include <iostream>
#include <exception>

using namespace std;
int main{
try{
try{
runtime_error s("error");
exception c(s);
throw c;
}
catch(exception &e){
cout<<"catch 1th!!"<<endl;
throw;
}
}catch(exception &e2){
cout<<"catch 2nd!!!"<<endl;
}
return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章