对于因为整数类型参与算术操作和类型转换时产生的“溢出异常”——System.OverflowException,在某些算法来讲不算真正的“异常”,相反这种溢出常常为程序所用。
C#通过引入checked和unchecked关键字来控制这种特殊情况的需求。它们都可以加于一个语句块前(如:checked{……}),或者一个算术表达式前(如:unchecked(x+y)),其中加checked标志的语句或表达式如果发生算术溢出,则抛出System.OverflowException类型的异常,而加unchecked标志的语句发生算术溢出时,则不抛出异常。
checked 和 unchecked 关键字只能适用于对 int 和 long 等整型执行的运算,不能使用它们来控制浮点(非整数)运算,因为浮点运算不会抛出 overflowException -- 即使让一个浮点数除以 0.0 。
代码如下所示:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace CheckedAndUnchecked
- {
- class Program
- {
- static void Main(string[] args)
- {
- checked // 打开整数溢出检查
- {
- try
- {
- int a = int.MaxValue;
- Console.WriteLine("a = {0}", a);
- a++; // a++ 后 a 已经超出了 int 的范围,发生异常,后面的代码不再执行
- Console.WriteLine("a = {0}", a);
- Console.WriteLine("运行不到此处");
- }
- catch (OverflowException oEx)
- {
- Console.WriteLine(oEx);
- }
- }
- unchecked // 关闭整数溢出检查
- {
- int a = int.MaxValue; // a = 2147483647
- Console.WriteLine("a = {0}", a);
- a++; // 虽然 a++ 后 a 已经超出 int 的范围
- // 但使用 unchecked 是此处不检查此异常,故后面的代码继续执行
- Console.WriteLine("a = {0}", a); // a = -2147483648,最大值 +1 变为最小值
- Console.WriteLine("可以运行到此处");
- }
- }
- }
- }
运行结果为:
以上转载自:http://blog.csdn.net/seattle1215/article/details/6660896
另附:
byte a,b,result;
a=b=127; // 127 字节码为:0111 1111
当result=a*b时,超出了byte类型的取值范围(0 ~ 255),导致溢出。 // 0111 1111 * 0111 1111 = 0000 0001 (溢出了)
此时便可用unchecked关键字使其不检查溢出,从而不会使程序出现异常而中断运行。如下:
result = uncheck((byte)(a * b));
result的运算结果为 1 。