[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Java arithmetic overflow (was Re: the benefits of immutability)




"James Y. Knight" <jknight@ai.mit.edu> writes:
> Perhaps arithmetic overflow detection should have been added. It
> certainly could be nice. However, I suspect Sun decided the cost was
> too great, since, AFAIK current processors don't have the ability to
> trap on integer overflow.

Actually, even MIPS will let you trap on overflow -- but it doesn't
have condition code registers. Most processors, more or less, will do
trap on overflow if asked.

Doing cheap MP arithmetic on MIPS is a bitch though -- you need to
manually check for overflow since there is no overflow bit. :(
PowerPC, ARM, etc. are fine on this.

> Thus, after every single integer operation,
> it would need to do a conditional jump on the overflow condition
> register flag. Certainly doable, though not very efficient.

Hey, given how dog slow the official language implementation is, who
would notice even if it took an extra few instructions per add (which
it wouldn't...)

> However, the big question is: what should it do when there is an
> overflow? If it throws an exception (RuntimeException subtype
> presumably so you don't need to declare it on every function), at
> least programs will fail loudly, but you'll have to write your code
> much more carefully to actually be able to continue working as there
> are now many more possible sites for an exception to occur.

I would rather a program terminate on an unintended overflow than that
it blithely continue running. There are huge numbers of dangerous and
utterly silent errors that happen as a result of unnoticed arithmetic
overflow, and figuring out where they happened is a royal
bitch. Throwing an exception seems like a fine way of doing it, but
really, anything else that is conspicuous would be fine.

Of course, silently converting to a bignum if you haven't explicitly
said a variable should only be a fixnum seems like a fine solution,
too. In Java's model, though, an exception likely makes more sense.


--
Perry E. Metzger		perry@piermont.com