# Wednesday, 31 July 2002
« No Title | Main | No Title »
What's wrong with this picture?
class DivTest
{
 public static void Main()
 {
  int i = int.MinValue;
  System.Console.WriteLine(-i);
  System.Console.WriteLine(i * -1);
  System.Console.WriteLine(i / -1);
 }
}

Why does div throw an OverflowException when you're trying to divide MinInt by -1? I'm assuming that since dividing by zero throws a DivideByZeroException, the CLR designers thought it would be nice if div would throw an exception for overflow as well.

This sucks!

Partition III CIL.doc section 3.31 about div says:

Exceptions:

Integral operations throw ArithmeticException if the result cannot be represented in the result type. This can happen if value1 is the maximum negative value, and value2 is -1.

Integral operations throw DivideByZeroException if value2 is zero.

Implementation Specific (Microsoft)

On the x86 an OverflowException is thrown when computing (minint div –1).

Why didn't they define a div.ovf (like there are add.ovf, sub.ovf, mul.ovf, etc.) in addition to div (and then make div behave consistently with add, submul)?

Question: What should I do? Implement Java's idiv bytecode using this broken div or compile them into conditional code that checks for MinInt / -1 and treats that specially (and thus slowing down integer division).

BTW, J# uses div but I'm not sure they actually thought about this issue. The following code crashes the J# compiler:

 System.out.println(Integer.MIN_VALUE / - 1);
Wednesday, 31 July 2002 16:14:23 (W. Europe Daylight Time, UTC+02:00)  #    Comments [2]