6

Is it possible to throw some sort of runtime exception when integer overflow occurs rather then failing silently. For e.g.

int x = 100000000 * 1000000000;

print 1569325056 due to overflow and what I w'd like is to get some sort of runtime exception

CubeJockey
  • 2,209
  • 8
  • 24
  • 31
adam.kubi
  • 1,753
  • 3
  • 13
  • 14

1 Answers1

14

Yes, Starting from Java-8 you can use the new Exact method, it will throw an exception(java.lang.ArithmeticException: integer overflow) on overflow. E.g.

Math.multiplyExact(100000000, 1000000000);
sol4me
  • 15,233
  • 5
  • 34
  • 34
  • 2
    @Trobbins Hope this time its fixed :) – sol4me May 01 '15 at 13:43
  • 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