5

I've got an integer array that contains two values, each the maximum value of int32:

int[] factors = new int[] { 2147483647, 2147483647 };

I'm trying to get the product of these two numbers to create an OverflowException:

try
{
    int product = factors[0] * factors [1];
}
catch(Exception ex)
{
}

Much to my surprise (and dismay), product actually returns a value of 1. Why is this, and how would I go about throwing an exception when the product of two integers exceeds int.MaxValue?

Jonathan Shay
  • 916
  • 8
  • 12

3 Answers3

9

Because the default behavior of C# is not to check overflow with int. However, you can force overflow checking by using checked keyword.

try
{
    checked
    {
        int product = factors[0] * factors [1];
    }
}
catch(Exception ex)
{
}
Cédric Bignon
  • 12,892
  • 3
  • 39
  • 51
2

You will have to call BigMul of the math class(used to multiply large integers and avoid overflow),or else even without exception,by using the * operator will result in 1.

long product = Math.BigMul(factors[0], factors[1]);

to throw the exception you will have to place checked.

checked
{
     int product = factors[0] * factors[1];
}

great tutorial about overflow by using the checked and unchecked

http://www.codeproject.com/Articles/7776/Arithmetic-Overflow-Checking-using-checked-uncheck

terrybozzio
  • 4,424
  • 1
  • 19
  • 25
0

You need to enclose it in a checked block to throw an overflow exception. Replace int product = factors[0] * factors [1]; with this:

checked
{
    int product = factors[0] * factors [1];
}

Without the checked block the result will be truncated since it exceeds int's maximum capacity.

pcnThird
  • 2,362
  • 2
  • 19
  • 33