#58 – Generate Exceptions on Integer Overflow Using Checked Operator

By default, when an overflow occurs as a result of an arithmetic operation on an integer type, the result wraps.

 int n1 = int.MaxValue;      // 2147483647 (0x7FFFFFFF)
 n1 = n1 + 1;                // Now -2147483648 (wrapped)

You can instead cause an exception to be thrown whenever an integer overflow condition occurs. To do this, use the checked keyword on the expression:

 int n1 = int.MaxValue;      // 2147483647 (0x7FFFFFFF)
 n1 = checked(n1 + 1);       // Throws OverflowException

You can also use the checked keyword on the statement block that contains the expression:

 checked
 {
     int n1 = int.MaxValue;   // 2147483647 (0x7FFFFFFF)
     n1 = n1 + 1;             // Throws OverflowException
 }

You can also make a change to your project so that the default behavior is to throw the exception, even without the checked keyword.  Go to Project Properties, click on Build tab, then click on the Advanced button at the bottom of the window.  This brings up the Advanced Build Settings dialog.

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 43 other followers