gpt4 book ai didi

java - 如何捕获 Spring MVC 中的整数溢出错误?

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:56:30 24 4
gpt4 key购买 nike

我正在使用 Spring MVC 3.0.5。对于映射到整数的字段,Spring 会愉快地忽略整数溢出。我该如何报告正确的错误?

最佳答案

这不是Spring的问题,是一般的Java问题。 Java 没有像 C 那样的溢出问题,但是它环绕整数。

@Test
public void demoIntegerWrapp(){
int value = Integer.MAX_VALUE;
value += 1;
assertEquals(Integer.MIN_VALUE, value);
}

所以你最好的想法是使用 long 进行计算并检查结果是否在整数范围内,否则抛出异常。

public int overflowSaveAdd(int summand1, int summand2) {
long sum = ((long) summand1) + ((long) summand2);
if (sum < Integer.MIN_VALUE ) || (sum > Integer.MAX_VALUE) {
throw new RuntimeException(sum + " is too big for integer");
} else {
return (int) sum;
}
}

关于java - 如何捕获 Spring MVC 中的整数溢出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6068263/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com