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关注打赏
最近更新
- 深拷贝和浅拷贝的区别(重点)
- 【Vue】走进Vue框架世界
- 【云服务器】项目部署—搭建网站—vue电商后台管理系统
- 【React介绍】 一文带你深入React
- 【React】React组件实例的三大属性之state,props,refs(你学废了吗)
- 【脚手架VueCLI】从零开始,创建一个VUE项目
- 【React】深入理解React组件生命周期----图文详解(含代码)
- 【React】DOM的Diffing算法是什么?以及DOM中key的作用----经典面试题
- 【React】1_使用React脚手架创建项目步骤--------详解(含项目结构说明)
- 【React】2_如何使用react脚手架写一个简单的页面?