1. 程式人生 > 程式設計 >C++異常重丟擲例項分析

C++異常重丟擲例項分析

如果我們編寫了一個函式,函式內部可能會出現異常,但是我們不想在這個函式內處理,而是想要通知呼叫者,那麼C++允許它重丟擲這個異常。語法如下:

try {
  //Execute some code    
} catch (Exception& e) {
  //Peform some operations before exits
  throw;
}

語句throw重新丟擲了異常。

看一個實際的例子:

#include <iostream>
#include <stdexcept>

using 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++異常重丟擲例項分析

知識點擴充套件

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
}

以上就是C++異常重丟擲例項分析的詳細內容,更多關於C++異常重丟擲的資料請關注我們其它相關文章!