2013-04-13 19 views
0

我在Snow Leapard下運行一個帶catch塊的C++程序來處理所有異常。該計劃是:Catch程序沒有在C++程序中執行

#include <iostream> 

using namespace std; 

const int DefaultSize = 10; 

int main() 
{ 
    int top = 90; 
    int bottom = 0; 

    try 
    { 
     cout << "top/2 = " << (top/ 2) << endl; 

     cout << "top divided by bottom = "; 
     cout << (top/bottom) << endl; 

     cout << "top/3 = " << (top/ 3) << endl; 
    } 
    catch(...) 
    { 
     cout << "something has gone wrong!" << endl; 
    } 

    cout << "Done." << endl; 
    return 0; 
} 

我使用G ++版本的i686-蘋果darwin10-G ++ - 4.2.1編譯程序:G ++ -o測試TEST.CPP。 catch塊沒有執行。輸出是:「top/2 = 45 浮點異常」。沒有錯誤信息或完成打印。輸出與try-catch塊不存在時完全相同。有人可以告訴我爲什麼捕捉不執行?我已經得到了用戶定義的異常工作。

回答

0

在C++中沒有默認的零分割錯誤。因此,您需要檢查底部值是否爲0

try{ 
    if(bottom==0) 
     throw bottom; //Or any integer 
    } 

catch(int x) 
{ 
    cout<<"Something has gone wrong"; 
}