您当前的位置: 首页 >  c#

C#OverflowException异常

发布时间:2021-10-11 16:20:51 ,浏览量:5

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:0)
System.Int32.Parse (System.String s, System.Globalization.NumberStyles style, System.IFormatProvider provider) (at: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

关注
打赏
1688896170
查看更多评论

暂无认证

  • 5浏览

    0关注

    115984博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0540s