1
int base, power, result = 1;   
for (int i = 1; i <= power; i++) {
    result *= base;
}
System.out.println(base + " to the power of " + power + " result: " + result);

10 to the power of 9 result: 1000000000 but;
10 to the power of 10 result: 1410065408

In my application this is logically an error but how can I detect this error before the println? for instance, when this error occurs, I want to print "result data type is int 32bit, it must not exceed 2,147,483,647"

How can I catch these kinds of errors?

1 Answer 1

1

https://www.baeldung.com/java-overflow-underflow I have found an enough answer here. I have corrected my code like this:

try {
    for (int i = 1; i <= power; i++) {
        result = Math.multiplyExact(base, result);
    }
} catch(ArithmeticException intSize) {
    base = result = 0;
    System.out.println("out of size int32: ")
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.