If I divide by zero I get a java.lang.ArithmeticException, as in this example :
int a = 3/0;
I'd like to make it so that an integer overflow also causes an Exception. So the following program would throw an exception rather than printing -2147483648.
public static void main(String[] args) {
int a = Integer.MAX_VALUE + 1;
System.out.println( a );
}
I know I could use BigInteger, which does not overflow and is only limited by available memory.
I know I could make my own add
function which checks for overflows. Or I could use Java 8 Math.addExact.
I realize I am asking for behaviour contrary to JLS at 15.18.2
If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format. If overflow occurs, then the sign of the result is not the same as the sign of the mathematical sum of the two operand values.
Besides modifying the source of a JVM and using such modified JVM. Is there any way to acomplish this? And even modifying the source of the JVM would not be enough, because libraries could depend on that behaviour and I don't want them to be affected by this, only my code.