7

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.

Anonymous Coward
  • 3,140
  • 22
  • 39

1 Answers1

6

I am sorry to say that, but you can not.

The only solution would be to write your own function or use Math#addExact, as you said.

Fabian Damken
  • 1,477
  • 1
  • 15
  • 24
  • Why not check if the next value would cause overflow? `if (x > Integer.MAX_VALUE - 1) { throw new Exception("Overflow"); }` –  May 09 '18 at 10:08
  • I thought he wanted a way of checking whether an overfow happened without writing the logic himself. Using Math#addExact, this is possible. – Fabian Damken May 09 '18 at 13:32
  • Besides that, take a look at the Code in [`Math#addExact(int, int)`](), it is not that trivial (for example, if `a` and `b` are big anough, `a + b` can be `> 0` too). – Fabian Damken May 09 '18 at 13:35