How to throw an exception when an integer overflows?

If I divide by zero, I get java.lang.ArithmeticException, as in this example:

int a = 3/0;

I would like to make integer overflow also throw an exception. Thus, the following program will throw an exception, not a print -2147483648.

public static void main(String[] args) {
    int a = Integer.MAX_VALUE + 1;
    System.out.println( a );
}

I know that I can use BigInteger, which is not full and limited only by available memory.

I know that I can create my own function addthat checks for overflow. Or I could use Java 8 Math.addExact .

I understand that I am asking for behavior contrary to JLS in 15.18.2

If the integer addition overflows, then the result is a low order of the bits of the mathematical sum, presented in some fairly large two-component format. If overflow occurs, then the sign of the result does not coincide with the sign of the mathematical sum of the two values โ€‹โ€‹of the operands.

Besides changing the source of the JVM and using such a modified JVM. Is there any way to do this? And even changing the source of the JVM will not be enough, because libraries can depend on this behavior, and I do not want them to be affected by this, only my code.

+4
source share
1 answer

I'm sorry to say that, but you cannot.

- Math # addExact, .

+5

Source: https://habr.com/ru/post/1650449/


All Articles