Java 8: Catching Integer Overflows 📎
In Java the addition: Integer.MAX_VALUE + Integer.MAX_VALUE
results in -2
without complaining.
The following unit test passes:
@Test
public void addWithOverflow() {
int result = Integer.MAX_VALUE + Integer.MAX_VALUE;
assertThat(result, is(-2));
}
Java 8 allows you to catch the overflows as ArithmeticException instances by using the Math.addExact (multiplyExact, subtractExact etc.) method.
The following test also passes:
@Rule
public ExpectedException expected = ExpectedException.none();
@Test
public void addWithOverflowAndCatch() {
expected.expect(ArithmeticException.class);
expected.expectMessage(containsString("integer overflow"));
Math.addExact(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.