2013-05-27

izard: (Default)
2013-05-27 08:06 am
Entry tags:

Division overflow exception: bug or feature?

Reinforcements are coming:

There were some comments to the previous posts on division overflow suggesting that throwing an exception is not appropriate.

E.g. [livejournal.com profile] fatoff thinks that throwing the exception in this case is not good.

Also, there was an idea that the right code for the job would look like:
return (int) ((long) x / (long) y);
which does not crash on signed int overflow. Unfortunately this code produces an incorrect result, which will almost certainly lead to a hard to find bug once the result is used in the future.

I believe "Fail-fast" is a good thing. The actors here are the C compiler, the CPU, and the programmer. Who should enable fail fast?

The C compiler cannot do it because behavior on signed integer overflow is undefined by the most recent C standards.

The programmer should be aware about the problem but we cannot count on it.

So throwing the exception which facilitates fail fast is a useful CPU feature. Besides, this X86 feature is well documented in the Intel manual.