Catching arithmetic overflow exceptions with C#’s checked keyword:

I was going through some reading material in the NET and found out an interesting situation which I would like to share with you

Never ever discount the destructive effects that arithmetic overflow exceptions bring to the stability of your software. For starters, recollect the tragic crash of the $7 billion Ariane 5 rocket – A crash that resulted because its software system attempted to convert a 64-bit floating-point number to a signed 16-bit integer, which subsequently caused an overflow exception, and worse yet, there was no exception handler to handle this exception. Sadly enough, the backup systems were also running on the same copy of the software, without the exception handler. Read an account of the Ariane 5 crash at:

http://www.cs.ucsd.edu/users/goguen/courses/230/ariane5nyt.pdf

 

Let’s face it – How many times have we been in situations where we’ve stared in disbelief at our program spewing some insanely odd numerical output on arithmetic operations when it’s fairly obvious that the output is in not even slightly connected to what was expected of the program. Let’s quickly see what we mean here with an example.

 

Consider the following C# program:

using System;

class ByteBites

{

static void Main(string[] args)

{

byte b1 = 57;

byte b2 = 200;

byte bResult = (byte)(b1 + b2);

Console.WriteLine("{0} + {1} = {2}", b1, b2, bResult);

}

}

Save this program to a file called ByteBites.cs. Compile the program using the following command from the DOS command line:

 

csc /taregets:exe ByteBites.cs

 

Run ByteBites.exe and observe the output:

57 + 200 = 1

57 + 200 = 1

Many of us know what went wrong here. It’s fairly obvious here that a byte data type can hold only values from 0 to 255. Yet we are trying to add two bytes whose result over shoots the range of values that the resultant byte can hold, resulting in an overflow, and hence the absurd result 1. This is what the less wary among us (at least I do) run into when choosing data types to work with, paying little attention to the range of data that the program expects these data types to store and handle. A subtle arithmetic addition operation that has the potential to generate an overflow operation is enough to send your application to the tomb. Most often, good testing practices catch these bugs during the testing phase. But it certainly might get past the QA team if the test data being fed to the program is not very exhaustive and if every possible test case is not being taken into account – The Ariane 5 crash of 1996 is a testimony to that. So as developers, we need to code defensively to catch such arithmetic overflow errors and handle them appropriately in the execution flow of the program as our application logic dictates, thus leaving no room for inconsistent or incorrect results to bring down the application to a grinding halt. So let’s see where C# can help us here. C# provides the checked keyword to trap and handle such arithmetic overflows. When an arithmetic operation that is enclosed within a checked block (or checked expression) results in an overflow, the runtime generates a System.OverflowException. Compare this to our previous example where the overflow result was silently assigned to the resulting byte. So let’s modify the previous example to enclose the arithmetic addition of the two bytes within a checked block. The modified code is shown below:

 

using System;

class ByteBites

{

static void Main(string[] args)

{

try

{

checked

{

byte b1 = 57;

byte b2 = 200;

byte bResult = (byte)(b1 + b2);

Console.WriteLine("{0} + {1} = {2}", b1, b2, bResult);

}

}

catch(OverflowException exOverflow)

{

Console.WriteLine("Caught overflow exception: {0}",

exOverflow.Message);

}

}

}

You’ll notice that we now have a checked block that encloses the arithmetic operation, which in turn is enclosed within a try block. Compile and run the application. Notice the output:

 

Caught overflow exception : Arithmetic Operation resulted an overflow.

Caught overflow exception: Arithmetic operation resulted in an overflow.

You’ll notice that the addition operation generated a System.OverflowException because it was enclosed within a checked block. Remove the checked block and you’ll notice that you’ll again get back the cryptic 1 as the result. But then, wouldn’t it be asking too much if we had to put each and every arithmetic operation that had the potential to generate an overflow within a checked block. Thankfully, there’s an easier way to turn on arithmetic overflow checking for the entire application by using the /checked compiler option when compiling your application. To test this, go ahead and remove the checked block that is enclosing the addition operation. This time compile the program with the /checked switch turned on, by typing the following command in the DOS command line:

 

csc /target:exe /checked ByteBites.cs

 

Run the program and observe the output that the program spews out:

Caught overflow exception: Arithmetic operation resulted in an overflow.

Notice that the /checked option has the same effect as using the checked block around your arithmetic operations. This option thereby allows you to enforce arithmetic overflow checks and to catch such exceptions throughout your application. So what if you’ve turned on the /checked option and want to selectively prevent certain parts in your application from generating an overflow exception when an overflow occurs. For example, assume you have a scenario where you need the check the value of the overflowed result to determine what action to take and so on. In such cases, you can use the unchecked keyword and enclose those arithmetic operations within an unchecked block so that an OverflowException is not generated for those operations. This is shown in the snippet of code below:

 

unchecked

{

byte b1 = 57;

byte b2 = 200;

byte bResult = (byte)(b1 + b2);

Console.WriteLine("{0} + {1} = {2}", b1, b2, bResult);

}

Of course, the above code fragment gives you yet another opportunity to see the infamous 1 as the result.

Using the checked keyword and /checked compiler option judiciously in your C# applications can help you catch arithmetic overflow exceptions and to ensure that your application stays sane.

 

===================
With Regards,
UVN PardhaSaradhi
http://spaces.msn.com/members/uvnpsaradhi/

Advertisements

2 thoughts on “Catching arithmetic overflow exceptions with C#’s checked keyword:

  1. Thanks a lot for yuor comment.I thought this is a very important topic which very few developers will look into.The emphasis of the developer always should be not only to complete their coding, but also to give quality coding by taking the advantage of the features given by the Lanaguage they use.-SARADHI

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s