CHAPTER 3 CORE C# PROGRAMMING CONSTRUCTS, PART I
byte sum = checked((byte)Add(b1, b2));
Console.WriteLine("sum = {0}", sum);
}
}
catch (OverflowException ex)
{
Console.WriteLine(ex.Message);
}
Notice that the return value of Add() has been wrapped within the scope of the checked keyword.
Because the sum is greater than a byte, we trigger a runtime exception. Notice the error message printed
out via the Message property:
Arithmetic operation resulted in an overflow.
If you wish to force overflow checking to occur over a block of code statements, you can do so by
defining a “checked scope” as follows:
try
{
checked
{
byte sum = (byte)Add(b1, b2);
Console.WriteLine("sum = {0}", sum);
}
}
catch (OverflowException ex)
{
Console.WriteLine(ex.Message);
}
In either case, the code in question will be evaluated for possible overflow conditions automatically,
which will trigger an overflow exception if encountered.
Setting Project-Wide Overflow Checking
If you are creating an application that should never allow silent overflow to occur, you might find
yourself in t he annoying position of wrapping numerous lines of code within the scope of the checked
keyword. As an alternative, the C# compiler supports the /checked flag. When enabled, all of your
arithmetic will be evaluated for overflow without the need to make use of the C# checked keyword. If
overflow has been discovered, you will still receive a runtime exception.
To enable this flag using Visual Studio, open your project’s property page and click the Advanced
button on the Build tab. From the resulting dialog box, select the Check for arithmetic
overflow/underflow check box (see Figure 3-3).
106