C#OverflowException异常

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.总结

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

 

 

posted on 2012-11-19 14:49  onedime  阅读(3492)  评论(0编辑  收藏  举报