C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Checked: We enable a checked context with the checked keyword. This can be activated through the compiler option "/checked."
Num: The variable "num" is incremented to the value equal to one plus the int.MaxValue, which cannot fit in the memory location.
IncrementThen: The runtime uses special intermediate language instructions and generates an OverflowException.
OverflowExceptionWarning: The variable "num" will not contain a logically correct value in the unchecked context.
C# program that uses checked overflow context
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++;
}
}
}
}
Output
Unhandled Exception: System.OverflowException:
Arithmetic operation resulted in an overflow.
at Program.Main()...
Tip: This feature specifies that overflow is an acceptable result of an operation such as increment—no exception is thrown.
Example: The program uses the short type, which cannot exceed the value 32767. The program increments the short and causes overflow.
short, ushortNote: In a checked context, an increment when the value is 32767 will throw an exception.
But: In an unchecked context, an increment will cause an overflow. The value will become invalid for most programs.
C# program that uses unchecked context
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);
}
}
}
Output
32767
-32669
Note: In the program shown, the "add.ovf" instruction is used instead of the simple "add" instruction.
Warning: The checked context will impose a substantial performance penalty if an overflow is detected.
ILAnd: This could prevent certain catastrophic errors related to large values becoming corrupted due to truncation.
Tip: You do not need to specify unchecked unless you have specified an enclosing checked context.
Tip 2: It is a good idea to use unchecked explicitly in cases where you are also using checked. This provides more symmetry.