I have the following try block to detect Integer overflow.
try {
Math.addExact((number % 10) * (int) Math.pow(10, i), reversedNumber);
} catch(ArithmeticException ae) {
return 0;
}
Okay, so if i run the above code as is, it causes an ArithmeticException as expected. However, if I want to assign the result of addExact
to an integer variable, the over flow is never detected.
try {
reversedNumber = Math.addExact((number % 10) * (int) Math.pow(10, i), reversedNumber);
} catch(ArithmeticException ae) {
return 0;
}
Can someone tell me why the exception isn't caught upon assignment to a variable? Is it because the assignment process is itself successful so no exception is thrown?
public static int reverse(int x) {
int number = Math.abs(x);
if(number == 0) return number;
int numberOfDigits = (int) Math.log10(number) + 1;
int reversedNumber = 0;
for(int i = numberOfDigits - 1; i >= 0; i--) {
try {
reversedNumber = Math.addExact((number % 10) * (int) Math.pow(10, i), reversedNumber);
} catch(ArithmeticException ae) {
return 0;
}
number /= 10;
}
return x < 0 ? -reversedNumber : reversedNumber;
}
with an input of 1534236469 the answer should be 0.