2011-02-10 31 views
1

我想玩處理意外的異常,但不能使它工作。這是自例如:C++ Reference意外的事情發生了

// set_unexpected example 
#include <iostream> 
#include <exception> 
using namespace std; 

void myunexpected() { 
    cerr << "unexpected called\n"; 
    throw 0;  // throws int (in exception-specification) 
} 

void myfunction() throw (int) { 
    throw 'x'; // throws char (not in exception-specification) 
} 

int main (void) { 
    set_unexpected (myunexpected); 
    try { 
    myfunction(); 
    } 
    catch (int) { cerr << "caught int\n"; } 
    catch (...) { cerr << "caught other exception (non-compliant compiler?)\n"; } 
    return 0; 
} 

他們說,輸出應該是: 輸出:

意外稱爲

抓INT

,當我嘗試這不會發生。我的輸出是:
捕獲其他異常
我使用VS2010 SP1

+3

「發生了意想不到的事情。」是的,例外情況就是這樣。 – 2011-02-10 09:21:47

+1

在`g ++`中,這種行爲是正確的;也許這是VS2010中的一個怪癖? – templatetypedef 2011-02-10 09:32:15

回答

6

unexpectedDocumentation說(不符合要求的編譯器?): C++標準要求,當一個函數拋出一個異常意外被稱爲是不在其投擲名單上。目前的實施不支持這一點。
所以答案是VC10是一個不兼容的編譯器。

0

Visual Studio沒有正確實施該標準。見this MSDN pageint被解析,但未被使用。

0

當函數有異常說明符時,Visual C++總是發出Warning C4290。從MSDN中的同一文章:「使用異常規範聲明函數,Visual C++接受但不執行該函數。」所以,這個編譯器不符合標準。