Differences between checked and unchecked

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.