← 中文资源

简体中文版本

addExact 溢出即时检测

普通加法溢出会静默回绕成负数,Math.addExact/multiplyExact/negateExact/toIntExact 则在溢出瞬间抛 ArithmeticException,让错误当场暴露而不是流向下游。

阅读英文原文

实现说明

活动部件是类 BudgetOverflow和函数 main。

使用要点

  • 跑完文件,输出里会留下标记——plain + 1 =、bumped =、addExact threw:。

常见问题

运行「addExact 溢出即时检测」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 plain + 1 =、bumped =、addExact threw: 标签标明各步骤。

核心语句

int bumped = Math.addExact(lastQty, 1);
Math.multiplyExact(3_000_000, 1_000);
Math.negateExact(Integer.MIN_VALUE);

代码示例

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());
        }
    }
}