C#數據進行顯示轉換時有可能會出現溢出的情況這時可以用關鍵字checked進行檢查是否溢出:
checked(<expression>) 檢查溢出
unchecked(<expression>) 不檢查溢出
如果使用checked檢查溢出,一旦溢出就會拋出System.OverflowException,同時也可以通過配置IDE來默認使能溢出檢查,除非加上unchecked,否則一旦溢出就會拋出異常,配置工程默認打開溢出檢查如下:

使用checked例子如下:
1 static void Main(string[] args)
2 {
3 Int32 a = 123456;
4 Int16 b = 0;
5
6 b = checked((Int16)a);
7
8 Console.WriteLine("a = {0}\r\nb = {1}", a, b);
9
10 Console.WriteLine("Press any key to exit!");
11 Console.ReadKey();
12 }
運行結果:
Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an overflow. at CheckOverflow.Program.Main(String[] args) in d:\Nick\code\C#\test\CheckOve rflow\CheckOverflow\Program.cs:line 16
轉換溢出拋出異常。