且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

csharp OverflowException——超出数值范围会抛出异常

更新时间:2022-09-16 21:48:12

OverflowException 會在下列情況下執行階段擲回︰

  • 算術運算會產生作業所傳回的資料型別範圍之外的結果。 下列範例說明 OverflowException 超出範圍的乘法運算所擲回 Int32 型別。

    int value = 780000000;
    checked {
    try {
       // Square the original value.
       int square = value * value; 
       Console.WriteLine("{0} ^ 2 = {1}", value, square);
    }
    catch (OverflowException) {
       double square = Math.Pow(value, 2);
       Console.WriteLine("Exception: {0} > {1:E}.", 
                         square, Int32.MaxValue);
    } }
    // The example displays the following output:
    //       Exception: 6.084E+17 > 2.147484E+009.
    
  • 轉型或轉換作業會執行縮小轉換,而來源資料類型的值超出範圍的目標資料類型。 下列範例說明 OverflowException 所擲回的嘗試將大型的不帶正負號的位元組值轉換為帶正負號的位元組值。

     
    byte value = 241;
    checked {
    try {
       sbyte newValue = (sbyte) value;
       Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", 
                         value.GetType().Name, value, 
                         newValue.GetType().Name, newValue);
    }
    catch (OverflowException) {
       Console.WriteLine("Exception: {0} > {1}.", value, SByte.MaxValue);
    } }                            
    // The example displays the following output:
    //       Exception: 241 > 127.
    

在每個案例中,運算的結果,是值小於 MinValue 屬性或大於 MaxValue 作業所產生的資料型別屬性。

算術、 轉型或轉換作業會擲回 OverflowException, ,作業必須發生在檢查的內容。 根據預設,會檢查的算術運算和 Visual Basic 中的溢位。在 C# 中,它們不是。 如果作業發生在未經檢查的內容,結果會截斷並捨棄任何不適合在目的型別的高序位位元。 下列範例說明這類未檢查的轉換在 C# 中。 它會重複先前的範例中未檢查的內容。

 
byte value = 241;
try {
   sbyte newValue = (sbyte) value;
   Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", 
                     value.GetType().Name, value, 
                     newValue.GetType().Name, newValue);
}
catch (OverflowException) {
   Console.WriteLine("Exception: {0} > {1}.", value, SByte.MaxValue);
}
// The example displays the following output:
//       Converted the Byte value 241 to the SByte value -15.

摘自:https://msdn.microsoft.com/zh-tw/library/system.overflowexception(v=vs.110).aspx






















本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/bonelee/p/6889426.html,如需转载请自行联系原作者