The development of a Java VM for .NET
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, sub & mul)?
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);
Or just wrap map java (x/y) to try{x/y} catch(OverflowException e) {x}. How much execution overhead is there for a try-catch in the non-exception case?
Remember Me
I apologize for the lameness of this, but the comment spam was driving me nuts. In order to be able to post a comment, you need to answer a simple question. Hopefully this question is easy enough not to annoy serious commenters, but hard enough to keep the spammers away.
Anti-Spam Question: What method on java.lang.System returns an object's original hashcode (i.e. the one that would be returned by java.lang.Object.hashCode() if it wasn't overridden)? (case is significant)