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,201
  • 8
  • 23
  • 31
adam.kubi
  • 1,683
  • 2
  • 12
  • 13

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
  • 14,603
  • 5
  • 33
  • 32