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:

        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:

        public ExpectedException expected = ExpectedException.none();
        public void addWithOverflowAndCatch() {
            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:


Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments