Nam G VU
Nam G VU

Reputation: 35404

How to get error/notification integer arithmetic overflow in Java?

Let's have a simple code as below

public class Sandbox {

    public static void run(String[] args) {
        int i = Integer.MAX_VALUE;
        int j = i+1;
        System.out.println(i);
        System.out.println(j);
    }
}

This will print output

2147483647

-2147483648

Value at j is overlowed without any notice to me when the code is executed.

I use Netbeans IDE to run this code.

Is it possible to configure the system to notify us when such arithmetic overflow occurs?

Upvotes: 2

Views: 1198

Answers (2)

user2212346
user2212346

Reputation: 78

In the Math API since Java 8, you can use:

Math.addExact(i, 1);

It will throw an ArithmeticException if the result overflows an int.

Upvotes: 1

halex
halex

Reputation: 16403

See the last sentence in the Java Language Specification (Chapter 15.18.2. Additive Operators (+ and -) for Numeric Types) :

Despite the fact that overflow, underflow, or loss of information may occur, evaluation of a numeric additive operator never throws a runtime exception.

For a lengthy article on this problem and the presentation of a tool for workaround see the article Signalling Integer Overflows in Java.

Upvotes: 4

Related Questions