2012-09-01 87 views
0

我目前得到以下方法,它返回我的百分比值。例如,物品價格爲35萬美元,百分比爲7%,則返回24,500。檢查計算是否超過MaxValue

public static decimal GetPercentValue(decimal? percentage, decimal baseValue) 
    { 
     decimal result = 0m; 

     if (percentage != null) 
     { 
      try 
      { 
       result = Convert.ToDecimal(baseValue * percentage/100m); 
      } 
      catch (OverflowException) 
      { 
       result = 0; 
       Logger.Warn("OverflowException caught in GetPercentValue() - should better be handled UI-Sided!"); 
      } 
     } 

     return result; 
    } 

我不認爲這是正確的方式處理,那麼有沒有什麼辦法可以避免這種情況下的異常?

當用戶輸入像999,999,999,999,999,999這樣的瘋狂號碼並計算其9999999999%時,會引發OverflowException。這種方式我不能檢查percentagebaseValue<= decimal.MaxValue只是因爲他們不是...計算結果本身然後超過小數範圍。

+0

'我不認爲這是正確的方式處理 - - 你是什麼意思?目前還不清楚你認爲正確的方式應該是什麼樣的。 – Oded

+0

如果你超過79228162514264337593543950335的最大值,你可能想重新考慮你的方法嗎? – coolmine

+0

@Oded我認爲這應該(或可能)是可能的,而不需要通過簡單的if語句導致「OverflowException」的鉅額費用。 – SeToY

回答

0

錯誤處理應該(很可能)在方法之外完成。現在你隱藏異常並返回錯誤的結果(發生錯誤時返回0)。你的方法的調用者不能判斷結果是否正確或者是否是由於OverflowException引起的。

我重寫這樣的方法:

public static decimal GetPercentValue(decimal? percentage, decimal baseValue) 
{ 
    if (percentage == null) 
     return 0; 

    return baseValue*(percentage.Value/100); 
} 

還可以選擇添加,用戶可以調用調用真正的方法之前檢查參數的驗證方法..可以顯示在UI驗證錯誤:

public static string ValidatePercentValue(decimal? percentage, decimal baseValue) 
{ 
    try 
    { 
     GetPercentValue(percentage, baseValue); 
     return null; 
    } 
    catch (Exception ex) 
    { 
     return ex.Message; 
    } 
} 

除此之外注意到...

baseValue*(percentage.Value/100) 

...比...

baseValue*percentage.Value/100 

嘗試計算decimal.MaxValue的100%。第一個工作,而第二個拋出一個OverflowException。

1

這是一個古老的問題,但我碰到類似的問題,並認爲提供了一個可能的替代解決方案。當兩個數字的計算產生的數字大於MaxValue時,問題就會發生。這導致異常,並且難以用通常的方法來測試:

decimal existingValue = decimal.MaxValue; 
decimal newValue = (decimal)100; 

//doesn't work -- exception thrown here 
if(existingValue + newValue <= decimal.MaxValue) 
{ 

} 

,似乎爲我工作(不使用try-catch塊)是重寫等式,在這種情況下,一個解決方案減法:

if(decimal.MaxValue - existingValue >= newValue) 
{ 
    //DoSomething 
} 

由於減法不超過MaxValue。我沒有嘗試乘法/除法的例子,但我猜測它也會起作用。