The checked and unchecked operators are used to control overflow checks in the current environment during integer arithmetic operations. The following operations are involved in the checked and unchecked checks (the operands are integers ):
1) pre-defined ++ and-unary operators.
2) predefined-unary operator.
3) predefined binary operators, such as +,-, X, And.
4) convert the display data from one integer to another.
When the preceding Integer Operation produces a large number that cannot be expressed by the target type, the corresponding processing method is available:
(1) Use checked
If the operation is a constant expression, a compilation error occurs: The operation overflows at complie time in checked mode.
If the operation is a non-constant expression, an overflow exception is thrown during running: overflowexception
(2) Use unchecked
No compilation error or runtime exception occurs regardless of whether the operation is a constant expression, but the return value is truncated to a high level that does not conform to the target type.
(3) Neither checked nor unchecked is used
If the operation is a constant expression, the overflow check is always performed by default. Like using checked, compilation fails.
If the operation is a non-constant expression, whether the overflow check is performed depends on external factors, including the compiler status and execution environment parameters.
The following example shows how to use the checked and unchecked operators in a non-constant expression:
Class Test
{
Static int x = 1000000;
Static int y = 1000000;
Static int F ()
{
Return checked (x * Y); // overflowexception exception thrown during runtime
}
Static int g ()
{
Return unchecked (x * Y); // returns the-727379968
}
Static int H ()
{
Return x * Y; // depends on the default settings of the compiler, which is generally not checked.
}
}
How to Use the checked and unchecked operators in constant expressions:
Class Test
{
Const int x = 1000000;
Const int y = 1000000;
Static int F ()
{
Return checked (x * Y); // compilation error. Compilation fails
}
Static int g ()
{
Return unchecked (x * Y); // returns the-727379968
}
Static int H ()
{
Return x * Y; // compilation error. Compilation fails
}
}