5 ms·
From `The CERT Oracle Secure Coding Standard for Java` public static int safeAdd(int l, int r) throws OverflowException { if (r > 0 ? l > Int
by muraty 12y ago
From `The CERT Oracle Secure Coding Standard for Java`
public static int safeAdd(int l, int r) throws OverflowException
{
if (r > 0
? l > Integer.MAX_VALUE - r
: l < Integer.MIN_VALUE - r)
throw new ArithmeticException(String.format(
"Integer overflow: %d + %d", l, r));
return l + r;
}
https://www.securecoding.cert.org/confluence/display/java/NUM00-J.+Detect+or+prevent+integer+overflow https://www.securecoding.cert.org/confluence/display/java/NU...
- jerven 12y agoIn java 8 you should probably use the Exact methods in java.lang.Math (In cases where the size is int or long and overflow errors need to be detected, the methods addExact, subtractExact, multiplyExact, and toIntExact throw an ArithmeticException when the results overflow)