The maximum value of the int type is 2147483647. the sum of the two maximum values exceeds the maximum value of the int type, that is, overflow occurs.
ClassProgram
{
Static VoidMain (String[] ARGs)
{
IntY = 2147483647;
IntX = 2147483647;
IntZ = x + y;
Console. writeline (Z. tostring ());
Console. readkey ();
}
}
Place the breakpoint in int z = x + y. The code line and one-step debugging show that the value of Z is-2. Because the maximum value of the int type is 2147483647, x + y exceeds the maximum value, and overflow occurs.
□Use checked
If we want the compiler to help us determine whether it is overflow, we will use the checked keyword.
ClassProgram
{
Static VoidMain (String[] ARGs)
{
IntY = 2147483647;
IntX = 2147483647;
IntZ =Checked(X + y );
}
}
Run and throw an overflow exception:
If we want to manually capture and print exceptions, we should write as follows:
ClassProgram
{
Static VoidMain (String[] ARGs)
{
IntY = 2147483647;
IntX = 2147483647;
Try
{
IntZ =Checked(X + y );
}
Catch(Overflowexception ex)
{
Console. writeline (ex. Message );
}
Console. readkey ();
}
}
Run,
□Use unchecked
Using unchecked will not throw an overflow exception.
ClassProgram
{
Static VoidMain (String[] ARGs)
{
IntY = 2147483647;
IntX = 2147483647;
IntZ =Unchecked(X + y );
Console. writeline (Z. tostring ());
Console. readkey ();
}
}
Result:-2
Conclusion: The checked keyword is used to check and capture overflow exceptions. The unchecked keyword is used to ignore overflow exceptions.