Math.addExact
throws exception on overflow
Since Java 8 there is a set of methods in the Math
class:
toIntExact(long)
addExact(int,int)
subtractExact(int,int)
multiplyExact(int,int)
…and versions for long as well.
Each of these methods throws ArithmeticException
if overflow happens. Otherwise they return the proper result if it fits within the range.
Example of addition:
int x = 2_000_000_000;
int y = 1_000_000_000;
try {
int result = Math.addExact(x, y);
System.out.println("The proper result is " + result);
} catch(ArithmeticException e) {
System.out.println("Sorry, " + e);
}
See this code run live at IdeOne.com.
Sorry, java.lang.ArithmeticException: integer overflow