功能描述

checked运算符通知运行时当溢出时抛出一个OverflowException异常,checked运算符可以用于++, --, -(一元), +, -, *, /以及整数类型之间的显示转换。

用于对整型类型算术运算和转换显式启用溢出检查。

注意事项

1.如果不选择使用Check关键字,则会出现数值溢出,
2.如果使用Check关键字,当出现数值溢出时,会弹出报错信息。

程序演示

1.未使用Check关键字,会出现数值溢出

  static void Main(string[] args)          {              int i = 10;                Console.WriteLine(2147483647 + i);              Console.ReadKey();

在这里插入图片描述

2.使用Check关键字,数值溢出时,会触发报错信息

 int i = 10;              Console.WriteLine(checked(2147483647 + i));              Console.ReadKey();

在这里插入图片描述

3.使用 checked 启用运行时溢出检查。用到的方法有Try…Catch。

  static int maxIntValue = 2147483647;         static int CheckMethod()          {              int z = 0;              try              {                  z = checked(maxIntValue + 10);              }              catch (System.OverflowException e)              {                  Console.WriteLine("Checked and Caught" + e.ToString());                }              return z;          }            static int UncheckedMethod()          {              int z = 0;              try              {                  z = maxIntValue + 10;              }              catch(System.OverflowException e)              {                  Console.WriteLine("Unchecked and Caught" + e.ToString());                }              return z;                         }          static void Main()          {             Console.WriteLine("\nChecked output valuse is:{0}",CheckMethod());              Console.WriteLine("\nUnChecked output valuse is:{0}",                  UncheckedMethod());              Console.ReadKey();          }

在这里插入图片描述