Math addExact Overflow Detection
Catch integer overflow when it happens: addExact, multiplyExact, negateExact, and toIntExact throw ArithmeticException instead of wrapping silently.
Code
public class BudgetOverflow {
public static void main(String[] args) {
int lastQty = Integer.MAX_VALUE;
// 普通加法静默回绕:2147483647 + 1 直接变成 -2147483648
System.out.println("plain + 1 = " + (lastQty + 1));
// addExact 在溢出瞬间抛 ArithmeticException,错误当场暴露
try {
int bumped = Math.addExact(lastQty, 1);
System.out.println("bumped = " + bumped);
} catch (ArithmeticException e) {
System.out.println("addExact threw: " + e.getMessage());
}
// multiplyExact 同样检测乘法溢出
try {
Math.multiplyExact(3_000_000, 1_000);
} catch (ArithmeticException e) {
System.out.println("multiplyExact threw: " + e.getMessage());
}
// negateExact:Integer.MIN_VALUE 取负数也放不下,照样抛
try {
Math.negateExact(Integer.MIN_VALUE);
} catch (ArithmeticException e) {
System.out.println("negateExact threw: " + e.getMessage());
}
// toIntExact:long 收窄到 int,装不下就抛
long bigCount = 4_000_000_000L;
try {
System.out.println("narrowed = " + Math.toIntExact(bigCount));
} catch (ArithmeticException e) {
System.out.println("toIntExact threw: " + e.getMessage());
}
}
}How the snippet works
Math addExact Overflow Detection is built around the class BudgetOverflow and the function main.
Using it
The run emits 7 labeled sections — plain + 1 =, bumped =, addExact threw:, multiplyExact threw:, negateExact threw:, narrowed =, toIntExact threw: — one per step.
Key statements
int bumped = Math.addExact(lastQty, 1);
Math.multiplyExact(3_000_000, 1_000);
Math.negateExact(Integer.MIN_VALUE);
Interactive Tools for This Topic
GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Vector Similarity CalculatorCompute Cosine Similarity, Dot Product, Euclidean L2, Manhattan L1, and Chebyshev distances between numeric vectors with dimension checks.
FAQ
- What does Math addExact Overflow Detection print when run?
- Run it as a complete program — the output lines carry labels such as `plain + 1 =`, `bumped =`, `addExact threw:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.