Throw a numerical overflow exception

Is it possible to eliminate some kind of exception at runtime when integer overflow occurs and then silent silence. For instance,

int x = 100000000 * 1000000000; 

print 1569325056 due to overflow, and I would like to get some kind of exception at runtime

+6
source share
1 answer

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

 Math.multiplyExact(100000000, 1000000000); 
+13
source

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


All Articles