歡迎您光臨本站 註冊首頁

C++異常重拋出實例分析

←手機掃碼閱讀     bom485332 @ 2020-05-05 , reply:0

如果我們編寫了一個函數,函數內部可能會出現異常,但是我們不想在這個函數內處理,而是想要通知調用者,那麼C++允許它重拋出這個異常。語法如下:
try { //Execute some code } catch (Exception& e) { //Peform some operations before exits throw; }
語句throw重新拋出了異常。
看一個實際的例子:
#include

#includeusing namespace std; int f(){ try{ throw runtime_error("Exception in f"); } catch(exception& e){ cout << "Exception caught in f" << endl; cout << e.what() << endl; throw; } } int main() { try{ f(); } catch(exception& e){ cout << "Exception caught in main" << endl; cout << e.what() << endl; } return 0; }
運行結果:
知識點擴展:
c++重新拋出異常
有可能單個catch不能完全處理一個異常,此時在進行了一些處理工作之後,需要將異常重新拋出,由函數調用鏈中更上層的函數來處理。重新拋出由“throw;”語句實現,throw後不跟表達式或類型。
“throw;”將重新拋出異常對象,它只能出現在catch或catch調用的函數中,如果出現在其它地方,會導致調用terminate函數。
被重新拋出的異常是原來的異常對象,不是catch形參。該異常類型取決於異常對象的動態類型,而不是catch形參的靜態類型。比如來自基類類型形參catch的重新拋出,可能實際拋出的是一個派生類對象。
只有當異常說明符是引用時,在catch中對形參的改變,才會傳播到重新拋出的異常對象中。
catch (my_error & eObj) { eObj.status = severeErr; throw; // the status member of the exception object is severeErr } catch (other_error eObj) { eObj.status = badErr; throw; // the status member of the exception rethrown is unchanged }

[bom485332 ] C++異常重拋出實例分析已經有278次圍觀

http://coctec.com/docs/c/language/show-post-232976.html