...
The three main techniques for detecting unintended integer overflow are:
- Pre-condition testing of the inputs. Check the inputs to each arithmetic operator to ensure that overflow cannot occur. Throw an
ArithmeticException
when the operation would overflow if it were performed, otherwise perform the operation. We call this technique "Pre-condition the inputs" hereafter, for convenience. - Use a larger type and downcast. Cast the inputs to the next larger primitive integer type and perform the arithmetic in the larger size. Check each intermediate result for overflow of the original smaller type; throw an
ArithmeticException
if the range check fails. Note that the range check must be performed after each arithmetic operation. Downcast the final result to the original smaller type before assigning to the result variable. This approach cannot be use for typelong
, becauselong
is already the largest primitive integer type. - Use
BigInteger
. Convert the inputs into objects of typeBigInteger
and perform all arithmetic usingBigInteger
methods. Throw anArithmeticException
if the final result is outside the range of the original smaller type, otherwise convert back to the intended result type.
...