Trap Arithmetic Overflow Exception
We developers have a lot of arithmetic calculations to be done in our logic, and Arithmetic overflow exceptions can go un-trapped resulting in incorrect output. Consider the following code example
December 1, 2004
We developers have a lot of arithmetic calculations to be done in our logic, and Arithmetic overflow exceptions can go un-trapped resulting in incorrect output. Consider the following code example
byte x=255,y=255, z ;
try
{
z = (byte)(x + y) ;
Response.Write(z.ToString());
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
The maximum value of Byte datatype is 255. We will have a Overflow exception here which should ideally be trapped and handled. But this piece of code runs without throwing an exception and we get the value of z as 254 which is obviously wrong.
In order to trap the exception, we need to use the checked keyword. Consider the following piece of code.
byte x=255,y=255, z ;
try
{
z = checked((byte)(x + y)) ;
Response.Write(z.ToString());
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
We have added the checked keyword to the code. This piece of code throws the appropriate exception and the following exception message is printed.
‘Arithmetic operation resulted in an overflow’.
The following code would also work in the same manner as the code above.
byte x=255,y=255, z ;
try
{
checked
{
z = (byte)(x + y) ;
}
Response.Write(z.ToString());
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
There also exists unchecked keyword, which works in the exact opposite manner as the checked keyword. Both these keywords can be used for blocks of code and for a code expression as illustrated above.
By default, the compiler allows arithmetic overflow and we tend to get wrong results with our operations. The /checked option can also be specified while compilation so the arithmetic overflow exceptions are thrown without using the keywords in the code.
About the Author
You May Also Like