C# Checked Context

Check illustration

When a number overflows, its value becomes invalid. Normally, this causes no exception to be thrown in C# programs. Inside a checked context, though, an exception is thrown. At the intermediate language level, overflow-checking instructions are used. With checked, errors can be prevented by catching overflow early.

Keywords

Key point: With checked, if you go past the MaxValue or below the MinValue on the number type, a managed exception occurs.

Example

Note

This example program uses the checked context. When you execute this program, an OverflowException will be generated and it will terminate the program. If you remove the checked context or change it to an 'unchecked' context, the exception will not be generated or thrown. However, the variable will not contain a logically correct value in the unchecked context because it cannot hold a large enough value.

Program that uses checked overflow context [C#]

class Program
{
    static void Main()
    {
	//
	// Use checked overflow context.
	//
	checked
	{
	    int num = 0;
	    for (int i = 0; i < int.MaxValue; i++) // Increment up to max
	    {
		num++;
	    }
	    for (int i = 0; i < int.MaxValue; i++) // Increment up to max again (error)
	    {
		num++;
	    }
	}
    }
}

Exception thrown by runtime

Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an overflow.
   at Program.Main()...

Overview. The program increments an integer up to the maximum value that an int type can store in the first loop. Then, when it tries to increment that variable again, an exception is thrown. However, the OverflowException is only thrown when a checked context is enabled, which is usually done with the checked keyword but can be activated through a compiler option (/checked).

Warning

OverflowException thrown. In the second iteration of the second loop, the variable 'num' is incremented to the value equal to one plus the int.MaxValue constant, which cannot fit in the bytes allocated to the int. The runtime employs special intermediate language instructions and generates an exception at this point. The exception's message is shown in the output text.

OverflowException

Note: Generally the checked context is unneeded, but if the results of a computation are critical to your task and there is a possibility the number ranges encountered will be very great, using the checked context can easily inform you of errors. This could prevent certain catastrophic errors related to large values becoming corrupted due to truncation.

Intermediate representation

.NET Framework information

The execution engine that interprets the intermediate language includes support for the "ovf" suffix on arithmetical operations. This suffix indicates that the execution engine should check for overflow and generate an exception if the variables overflow. In the program text shown, the "add.ovf" instruction is used instead of the simple "add" instruction. The checked context will impose a substantial performance penalty if an overflow is detected.

Intermediate Language

Summary

The C# programming language

We looked at the checked context in the C# programming language, which clearly changes the behavior of the execution engine on certain arithmetical instructions when the minimum or maximum value of the type is passed.

Unchecked Context Exception Handling
.NET