为什么每个 API 不抛出异常?:
Returns the argument incremented by one, throwing an exception if the result overflows an int.
System.out.println(Math.incrementExact(2_147_483_647 + 1));
返回-2147483647
最佳答案
这是因为您将 Integer.MIN_VALUE
传递给 Math.incrementExact
函数。
您的表达式 2_147_483_647 + 1
首先被求值,由于它溢出,结果为 -2147483648
。然后将其传递给 Math.incrementExact
,结果为 -2147483647
。
你想做的是
System.out.println(Math.incrementExact(2_147_483_647));
这会导致java.lang.ArithmeticException:整数溢出
。
关于java - Math.incrementExact(int a),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50524904/