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

Peter_Gao_

暂无认证

  • 0浏览

    0关注

    621博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

C#OverflowException异常

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

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.MinValue && number             
关注
打赏
1664521772
查看更多评论
立即登录/注册

微信扫码登录

0.1276s