关于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。

posted on 2020-05-09 08:27  活着的虫子  阅读(6447)  评论(0编辑  收藏  举报

导航