I want to handle the special case where multiplying two numbers together causes an overflow. The code looks something like this:
int a = 20;
long b = 30;
// if a or b are big enough, this result will silently overflow
long c = a * b;
That's a simplified version. In the real program a and b are sourced elsewhere at runtime. What I want to achieve is something like this:
long c;
if (a * b will overflow) {
c = Long.MAX_VALUE;
} else {
c = a * b;
}
How do you suggest I best code this?
Update: a and b are always non-negative in my scenario.
解决方案
Java 8 has Math.multiplyExact, Math.addExact etc. for ints and long. These throw an unchecked ArithmeticException on overflow.