2013-07-21 13 views
2

我有一個包含兩個值,每個INT32的最大值一個整數數組:我試圖C#倍率值int.MaxValue的兩個變量不會導致發生OverflowException

int[] factors = new int[] { 2147483647, 2147483647 }; 

獲得這兩個數的乘積來創建一個OverflowException異常:

try 
{ 
    int product = factors[0] * factors [1]; 
} 
catch(Exception ex) 
{ 
} 

出乎我的意料(和沮喪),產品實際上返回值1。這是爲什麼,我怎麼會去拋出一個異常時,兩個整數的乘積超過int.MaxValue?

+0

你能不能讓 '產品' 的Int64? –

回答

6

因爲C#的默認行爲不是用int來檢查溢出。 但是,您可以使用checked關鍵字強制執行溢出檢查。

try 
{ 
    checked 
    { 
     int product = factors[0] * factors [1]; 
    } 
} 
catch(Exception ex) 
{ 
} 
+2

這是正確的 - 請注意,編譯器上還有一個「默認使用選中狀態」選項。 –

0

您需要將它放在checked塊中以引發溢出異常。更換int product = factors[0] * factors [1];本:

checked 
{ 
    int product = factors[0] * factors [1]; 
} 

沒有checked塊,因爲它超過int的最大容量的結果將被截斷。

相關問題