Exception handling calculate power
Is there any way to use Exception handling in a better way in such questions?


What you have is a very good start.

I would suggest refining your exception type where possible. In your case, I would suggest using IllegalArgumentException. Using a specific subtype helps with diagnosing/debugging.

Additionally, since IllegalArgumentException is a type of RuntimeException, you can then remove the throws Exception from your method signature.

long power(int n, int p) {
    if (n == 0 &amp;&amp; p == 0) {
        throw new IllegalArgumentException("n and p should not be zero.");
    } else if (n &lt; 0 || p &lt; 0) {
        throw new IllegalArgumentException("n or p should not be negative.");
    }

    return (long) Math.pow(n, p);
}