【问题标题】:Throw exception on numeric overflow [duplicate]在数字溢出时引发异常[重复]
【发布时间】:2015-07-11 07:37:40
【问题描述】:

当整数溢出发生而不是静默失败时,是否可以抛出某种运行时异常。例如

int x = 100000000 * 1000000000;

由于溢出而打印1569325056,我想要的是获得某种运行时异常

【问题讨论】:

    标签: java java-8


    【解决方案1】:

    是的,从 Java-8 开始,您可以使用新的 Exact 方法,它会在溢出时抛出异常(java.lang.ArithmeticException: integer overflow)。例如

    Math.multiplyExact(100000000, 1000000000);
    

    【讨论】:

    • @Trobbins 希望这次是固定的 :)
    • 为什么不检查下一个值是否会导致溢出? if (x > Integer.MAX_VALUE - 1) { throw new Exception("Overflow"); }
    猜你喜欢
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 2017-03-31
    • 1970-01-01
    • 1970-01-01
    • 2019-01-03
    相关资源
    最近更新 更多