Champ
Champ

Reputation: 1361

How to catch the Integer overflow error in Spring MVC?

I am using Spring MVC 3.0.5. Spring happily ignores an Integer overflow for a field that is mapped to an Integer. How can I report a proper error on that ?

Upvotes: 3

Views: 1150

Answers (2)

reprogrammer
reprogrammer

Reputation: 14728

There are Java libraries that provide safe arithmetic operations, which check integer overflow/underflow. For example, Guava's IntMath.checkedAdd(int a, int b) returns the sum of a and b, provided it does not overflow, and throws ArithmeticException if a + b overflows in signed int arithmetic.

Upvotes: 1

Ralph
Ralph

Reputation: 120881

It is not a Spring problem, it is a general Java Problem. Java has no overflow problem like C, but it wraps around the integer.

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

So the best think you can do is using long for calculation and check if the result is in the range of interger, else 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;
  }
}

Upvotes: 4

Related Questions