關於System.OverflowException異常


什么是OverflowException

就是溢出異常。這個一般是當在線程檢查的上下文中執行的算術、強制轉換或轉換運算導致溢出時引發的異常。

繼承
Object
Exception
SystemException
ArithmeticException
OverflowException

說明

  • 在運行時,將在以下條件下引發 OverflowException

    算術運算生成的結果超出了該操作所返回的數據類型的范圍。 下面的示例演示溢出 Int32 類型邊界的乘法運算所引發的 OverflowException
    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 
  • 以下 Microsoft 中間語言(MSIL)指令引發 OverflowException
    • add.ovf. <signed>

    • conv.ovf. <to type>

    • conv.ovf. <to type> .un

    • mul.ovf. <type>

    • sub.ovf. <type>

    • newarr

HRESULT

OverflowException 使用值為0x80131516 的 HRESULT COR_E_OVERFLOW。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM