2010-06-24 151 views
0

用下面的代碼,我得到了「Gotcha!」與蟒蛇。python異常與C++異常處理

 
try: 
    x = 0 
    y = 3/x 
except Exception: 
    # ZeroDivisionError 
    print "Gotcha!" 

我認爲這是等價的C++代碼,但它無法捕捉到這個exeption。

#include <iostream> 

int main() 
{ 
    int x = 0; 
    //float y = 3.0/x; 
    int z = 0; 

    try { 
     z = 3/x; 
    } catch (std::exception) { 
     std::cout << "Gotcha!"; 
    } 

    std::cout << z; 
} 
 
Floating point exception 

出了什麼問題? 我怎樣才能捕捉到這個異常?

+1

相關:[如何在Linux C++中捕獲系統級異常?](http://stackoverflow.com/questions/618215/how-do-i-catch-system-level-exceptions-in-linux- c) – miku 2010-06-24 21:14:44

+0

對於Windows特定的角度來看這個問題:http://stackoverflow.com/questions/1909967/what-does-msvc-6-throw-when-an-integer-divide-by-zero-occurs – 2010-06-24 21:16:09

回答

5

在C++中,除以零不會產生異常;它會導致未定義的行爲。

必須在實際執行除法之前檢查您的除數,因爲如果您確實使用零除數來評估除法表達式,將無法知道會發生什麼。