Checked and unchecked
For an "overflow exception"--system.overflowexception that occurs when an integer type participates in arithmetic operations and type conversions, in some algorithms it is not a true "exception", which is often used by the program instead. C # controls the need for this particular situation by introducing checked and unchecked keywords. They can all be added to a block of statements (such as: checked{...} ), or an arithmetic expression before (for example: Unchecked (x+y)), where a statement or expression with the checked flag has an arithmetic overflow, Throws an exception of type System.OverflowException, while the statement with the unchecked flag has an arithmetic overflow and does not throw an exception. Here is an example:
using system;using system.collections.generic;using System.Linq;using System.text;namespace consoleapplication1{class Program {Private delegate string getastring (); static void Main (string[] args) {int num1 = 100000, num2 = 100000,result = 0; Checked {try {result = Num1 * NUM2;} catch (Exception e) {Console.WriteLine (e);} Finally {Console.WriteLine (result);} } unchecked {try {result = Num1 * NUM2;} catch (System.OverflowException e) {Console.WriteLine (e);} Finally {Console.WriteLine (result);} } try {result = Num1 * NUM2;} catch (System.OverflowException e) {Console.WriteLine (e);} Finally {Console.WriteLine (result);} Console.read (); } } }
Program output:
As you see, by default it is unchecked
You can see the same arithmetic operation, throw an overflow exception with checked, and unchecked just discard the overflow bit and get the remaining 32-bit decimal integer value. It is worth noting that the code for the entire file can be specified with the "/checked" compiler option as checked semantics, and defaults to unchecked if not specified. If you also specify the checked or unchecked flag in your program code, with the checked compiler option, the remainder has checked semantics in addition to the code that is marked unchecked.
What is the meaning of unchecked in C # and what does it do?