2017-07-28 70 views
0

我正在處理這段代碼,並且發現該方法在成功調用後不會拋出異常。如果我使用std :: cout一切正常,並引發異常。我使用的是gcc版本4.9.2(Debian 4.9.2-10)。它是一個海灣合作委員會的錯誤或STL錯誤的代碼問題或還有什麼?這段C++代碼的奇怪行爲(std :: wcout和std :: exception)

// exceptions 
#include <iostream> 
using namespace std; 
class C { 
    public: 
    string srch(int &i) { 
     if (i == 0) { //found 
      wcout << "got it: " << i << endl; return "i"; 
     } 
     throw std::exception(); 

    } 

}; 

int main() { 
    C c = C(); 
    int i = 2; 
    int j = 0; 
    try 
    { 
    c.srch(j); 
    c.srch(i); 
    } 
    catch (const std::exception &e) { 
    cout << "An exception occurred. Exception Nr. " << e.what() << '\n'; 
    } 
    return 0; 
} 

下面是一個ideone link to reproduce the lack of an exception with wcout.a link reproducing the exception when cout is used

回答

2

您的示例不是證明不引發異常。

您的catch塊中的cout消息不會顯示,因爲您已經使用wcout,並且在同一設備(stdout)上混合字符寬度爲未定義行爲。

cout更改爲wcout,您將看到異常,您只是沒有看到預期的消息。