2017-07-28 72 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,您将看到异常,您只是没有看到预期的消息。