C#OverflowException异常

OverflowException: Value was either too large or too small for an Int32.
System.Number.ParseInt32 (System.String s, System.Globalization.NumberStyles style, System.Globalization.NumberFormatInfo info) (at <d7ac571ca2d04b2f981d0d886fa067cf>:0)
System.Int32.Parse (System.String s, System.Globalization.NumberStyles style, System.IFormatProvider provider) (at <d7ac571ca2d04b2f981d0d886fa067cf>:0)

1.前言

  某日,在调试程序时,运行到“ntemp = Convert.ToInt32(UpNumber.Text, 16);”这句时突然蹦出一个对话框报告“OverflowException”。抓图如下:

2.分析原因

  查看UpNumber.Text的值为“11111111111111111111111111”,而Int32的取值范围是[-2147483648, 2147483647],用十六进制表示是[0x80000000,0x7FFFFFFF]而字符串“11111111111111111111111111”转换成Int32类型后结果是0x11111111111111111111111111,显然超出了Int32的取值范围,因此报告“OverflowException”。

3.解决办法

  解决办法有二,

其一是在程序中加入异常处理,参考代码如下:

复制代码

 1 // Create a hexadecimal value out of range of the Integer type.
 2 string value = Convert.ToString((long) int.MaxValue + 1, 16);
 3 // Convert it back to a number.
 4 try
 5 {
 6    int number = Convert.ToInt32(value, 16);
 7    Console.WriteLine("0x{0} converts to {1}.", value, number.ToString());
 8 }
 9 catch (OverflowException)
10 {
11    Console.WriteLine("Unable to convert '0x{0}' to an integer.", value);
12 }   

复制代码

  

其二是对待转换的变量进行上下限检查,参考代码如下:

复制代码

 1 long[] numbersToConvert = { 162345, 32183, -54000, Int64.MaxValue/2 };
 2 int newNumber;
 3 foreach (long number in numbersToConvert)
 4 {
 5    if (number >= Int32.MinValue && number <= Int32.MaxValue)
 6    {
 7       newNumber = Convert.ToInt32(number);
 8       Console.WriteLine("Successfully converted {0} to an Int32.", 
 9                         newNumber);
10    }
11    else
12    {
13       Console.WriteLine("Unable to convert {0} to an Int32.", number);
14    }
15 }

复制代码

  通过以上两种方法可以确保程序的健壮性。

4.总结

  这种问题很容易发生在编程新手中,一定要采取相应的措施,否则将可能导致程序在运行中突然崩溃,这是用户所不能容忍的。

    如果这个值并不重要,当超出上限时可以直接传此上限值,避开崩溃,如果这个值确实需要使用

,则考虑更换数据类型。

 
   if (number >= Int32.MinValue && number <= Int32.MaxValue)
   {
      newNumber = Convert.ToInt32(number);
      Console.WriteLine("Successfully converted {0} to an Int32.",
                        newNumber);
   }

   if(number < Int32.MinValue)
   {

      newNumber = Int32.MinValue;
      Console.WriteLine("Unable to convert {0} to an Int32. 为防越界崩溃,临时转为Int32最小值", number);
   }

   if(number > Int32.MaxValue)
   {

      newNumber = Int32.MaxValue;
      Console.WriteLine("Unable to convert {0} to an Int32. 为防越界崩溃,临时转为Int32最大值", number);
   }

 C#OverflowException异常 - onedime - 博客园

C# 变量值溢出和方法值溢出,以及OverflowException异常捕捉和处理_number1killer的博客-CSDN博客_overflowexception

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值