C# checked 和 unchecked

对于因为整数类型参与算术操作和类型转换时产生的“溢出异常”——System.OverflowException,在某些算法来讲不算真正的“异常”,相反这种溢出常常为程序所用。

      C#通过引入checked和unchecked关键字来控制这种特殊情况的需求。它们都可以加于一个语句块前(如:checked{……}),或者一个算术表达式前(如:unchecked(x+y)),其中加checked标志的语句或表达式如果发生算术溢出,则抛出System.OverflowException类型的异常,而加unchecked标志的语句发生算术溢出时,则不抛出异常

      checked  和 unchecked 关键字只能适用于对 int 和 long 等整型执行的运算,不能使用它们来控制浮点(非整数)运算,因为浮点运算不会抛出 overflowException -- 即使让一个浮点数除以  0.0  。

代码如下所示:

[csharp]  view plain copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace CheckedAndUnchecked  
  7. {  
  8.     class Program  
  9.     {  
  10.         static void Main(string[] args)  
  11.         {  
  12.             checked    // 打开整数溢出检查  
  13.             {  
  14.                 try  
  15.                 {  
  16.                     int a = int.MaxValue;  
  17.   
  18.                     Console.WriteLine("a = {0}", a);  
  19.                     a++;    // a++ 后 a 已经超出了 int 的范围,发生异常,后面的代码不再执行  
  20.                     Console.WriteLine("a = {0}", a);      
  21.                     Console.WriteLine("运行不到此处");  
  22.                 }  
  23.   
  24.                 catch (OverflowException oEx)  
  25.                 {  
  26.                     Console.WriteLine(oEx);  
  27.                 }  
  28.             }  
  29.   
  30.             unchecked    // 关闭整数溢出检查  
  31.             {  
  32.                 int a = int.MaxValue;   // a = 2147483647  
  33.   
  34.                 Console.WriteLine("a = {0}", a);  
  35.                 a++;    // 虽然 a++ 后 a 已经超出 int 的范围  
  36.                         // 但使用 unchecked 是此处不检查此异常,故后面的代码继续执行  
  37.                 Console.WriteLine("a = {0}", a);  // a = -2147483648,最大值 +1 变为最小值  
  38.                 Console.WriteLine("可以运行到此处");     
  39.             }  
  40.         }  
  41.     }  
  42. }  

运行结果为:


以上转载自: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 。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值