Detect overflow before recording a total in Java
Adding one to the largest int exceeds its range. Use addExact to make overflow an explicit outcome that the caller can handle.
A simple example
Use checked addition
- Start with 2 and 1
- Do this Use checked addition
- Result 3
Apply it to a real problem
- Start with Counters at 41 and at the integer limit
- Do this Try to register one more item
- Result 42 or capacity exceeded
Advertisements
Run the example
Save as Main.java and run java Main.java with JDK 21.
public class Main {
public static void main(String[] args) throws Exception {
for (int current : new int[]{41, Integer.MAX_VALUE}) {
try {
System.out.println(Math.addExact(current, 1));
} catch (ArithmeticException overflow) {
System.out.println("capacity exceeded");
}
}
}
}
42 capacity exceeded