Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0061 Check runtime overflow

checked operator checks the runtime overflow. The checked operator tells the runtime to generate an OverflowException. using System; class Program { static void Main(string[] args) { int i = int.MinValue; int result = checked(i - 1); Console.WriteLine("i=" + i); Console.WriteLine("result="+result); Console.WriteLine("result is int.MaxValue:" + (result == int.MaxValue)); } } The output: Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an overflow. at Program.Main(String[] args) Other than expression checking shown in the code above, checked operator can also check a block of code. using System; class Program { static void Main(string[] args) { int i = int.MinValue; checked { int result = i - 1; Console.WriteLine("i=" + i); Console.WriteLine("result=" + result); Console.WriteLine("result is int.MaxValue:" + (result == int.MaxValue)); } } } The output: Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an overflow. at Program.Main(String[] args)