Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw exception on numeric overflow [duplicate]

Tags:

java

java-8

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

like image 708
adam.kubi Avatar asked May 01 '15 13:05

adam.kubi


1 Answers

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);
like image 148
sol4me Avatar answered Sep 19 '22 02:09

sol4me