Difference between checked and unchecked: checkedunchecked
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.
class Program
{
static void Main(string[] args)
{
int y = 2147483647;
int x = 2147483647;
int z = 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.
class Program
{
static void Main(string[] args)
{
int y = 2147483647;
int x = 2147483647;
int z = checked(x + y);
}
}
Run and throw an overflow exception:
If we want to manually capture and print exceptions, we should write as follows:
class Program
{
static void Main(string[] args)
{
int y = 2147483647;
int x = 2147483647;
try
{
int z = checked(x + y);
}
catch (OverflowException ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadKey();
}
}
Run,
□Use unchecked
Using unchecked will not throw an overflow exception.
class Program
{
static void Main(string[] args)
{
int y = 2147483647;
int x = 2147483647;
int z = 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.
Different checked and unchecked
The former is checked in the check box, and the latter is not checked.
The difference between checked (expression) and unchecked (expression)
Short a = 32767;
Short B = 32767;
Short c = (short) (a + B );
Console. WriteLine (c );
The Result c is-2, which is obviously not correct. The key is that the program runs without prompting an error, and a result bug may occur.
Try
{
Short a = 32767;
Short B = 32767;
Short c = checked (short) (a + B ));
Console. WriteLine (c );
}
Catch (OverflowException e)
{
Console. WriteLine (e. Message );
}
Use checked to check for errors.