Checked in C# adds exceptions on number overflows. When a number overflows, its value becomes invalid. Normally, this causes no exception to be thrown.
Inside a checked context, though, an exception is thrown. With checked, errors can be prevented by catching overflow early. This leads to higher-quality programs.
When we execute this program, an OverflowException
will be generated and it will terminate the program. If we remove the checked context, the exception will not be thrown.
int.MaxValue
, which cannot fit in the memory location.OverflowException
.class Program { static void Main() { // // Use checked overflow context. // checked { // Increment up to max. int num = 0; for (int i = 0; i < int.MaxValue; i++) { num++; } // Increment up to max again (error). for (int i = 0; i < int.MaxValue; i++) { num++; } } } }Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an overflow. at Program.Main()...
Numeric types cause no exceptions when they overflow. This is the default behavior. It is also specified with the unchecked keyword.
short
type, which cannot exceed the value 32767. The program increments the short
and causes overflow.using System; class Program { static void Main() { // The first short will overflow after the second short does. short a = 0; short b = 100; try { // // Keep incrementing the shorts until an exception is thrown. // ... This is terrible program design. // while (true) { checked { a++; } unchecked { b++; } } } catch { // Display the value of the shorts when overflow exception occurs. Console.WriteLine(a); Console.WriteLine(b); } } }32767 -32669
The execution engine includes support for the "ovf
" suffix on arithmetical operations. This suffix indicates that the execution engine should check for overflow.
add.ovf
" instruction is used instead of the simple "add" instruction.If the results of a computation are critical and there is a possibility the number ranges encountered will be large, using the checked context can easily inform you of errors.
The checked context is more often useful than the unchecked context. This is because the unchecked context is the default when compiling C# programs.
The checked keyword affects integer manipulations. It changes the behavior of the execution engine on certain arithmetical instructions. Unchecked eliminates these checks.