C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
Tip: With checked, errors can be prevented by catching overflow early. This leads to higher-quality programs.
Tip 2: If you go past the MaxValue or below the MinValue on the number type, a managed exception occurs.
Example. This example program uses the checked context. When you execute this program, an OverflowException will be generated and it will terminate the program. In this way, it shows the effect of a checked context.
If you remove the checked context, the exception will not be generated or thrown. But the variable will not contain a logically correct value in the unchecked context. It cannot hold a large enough value.
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++; } } } } Exception thrown by runtime Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an overflow. at Program.Main()...
The program increments an integer up to the maximum value that an int type can store. When it tries to increment that variable again, an exception is thrown. The OverflowException is only thrown when a checked context is enabled.
Tip: This is usually done with the checked keyword but can be activated through a compiler option (/checked).
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.
Then: The runtime uses special intermediate language instructions and generates an exception.
Discussion. Generally, the checked context is unneeded. But 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.
And: This could prevent certain catastrophic errors related to large values becoming corrupted due to truncation.
Instructions. The execution engine 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 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.
Summary. The checked keyword affects integer manipulations. It changes the behavior of the execution engine on certain arithmetical instructions when the minimum or maximum value of the type is passed.