2011-06-20 74 views
2
#include <iostream> 
using namespace std; 
#include <exception> 

void dis() 
{ 
    cout<<"terminate disabled "<< endl; 
} 

void display() throw(int,double)  
{ 
    if(0) 
     throw int(); 
    if(0) 
     throw double(); 
    if(1) 
     throw string(); 
} 

int main() 
{  
    set_unexpected(dis); 
    try 
    { 
     display();  
    } 
    catch(int) 
    { 
     cout<<"int "<< endl; 
    } 
    catch(double) 
    { 
     cout<<"double "<< endl; 
    } 
    catch(string) 
    { 
     cout<<"string "<< endl; 
    } 

    system("pause"); 
    return 0; 
}  

現在的產量爲異常處理

terminate disabled 

,然後程序終止

而是的set_unexpected時,我寫

set_terminate(dis); 

產量爲

terminate disabled 
terminate disabled 

爲什麼這個dicrepancy?

+0

你不應該在'using namespace std;'語句下包含頭部。 – rubenvb

+0

@als它是互聯網上給出的GCC的Mingw端口 – avinash

+0

我寧願擺脫異常規範,而不是找出它們。異常規範可能很難獲得並保持正確,模板非常糟糕,並且類型系統複雜化等等。 –

回答

1

所以,這並不完全清楚你的原始輸出是什麼。我試圖儘可能清理它,但是你的報價標籤使它不明顯。

在你的代碼,如果你使用set_unexpected(dis),你應該看到:

terminate disabled 

在你的代碼,如果你使用set_terminate(dis),你應該看到:

terminate disabled 

在你的代碼,如果你使用set_unexpected(dis)set_terminate(dis),您應該看到:

terminate disabled 
terminate disabled 

解決此問題的一種方法是將dis throw 0作爲最後一行。這將允許你將你的異常轉換爲你的函數聲稱它會拋出的東西。

+0

我不明白,在他的代碼中,displa()拋出string(),並且在他的main()中,字符串異常被捕獲,不是嗎? dis爲什麼被觸發? – Alcott

+0

@Alcott:他使用[exception specifier](http://www.cplusplus.com/doc/tutorial/exceptions/)。正因爲如此,函數應該只返回在那裏指定的類型。 –