How to catch Integer overflow error in Spring MVC?

I am using Spring MVC 3.0.5. Spring happily ignores Integer overflow for the field that maps to Integer. How can I report the correct error?

+3
source share
2 answers

This is not a Spring problem, it is a common Java problem. Java does not have an overflow problem like C, but it wraps around an integer.

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

Therefore, it is best to think that you can use long to calculate and check if the result is in the interger range, otherwise throw an exception.

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;
  }
}
+4
source

Java, , / . , Guava IntMath.checkedAdd(int a, int b) a b, , ArithmeticException, a + b int.

+1

All Articles