Exception handling calculate power I've to create a class MyCalculator which consists of a single method long power(int, int). This method takes two integers,  and, as parameters and finds Math.pow(n,p).
- If either n or p is negative, then the method must throw an exception which says "n or p should not be negative.".
- If both n and p are zero, then the method must throw an exception which says "n and p should not be zero."

class MyCalculator {
    /*
    * Create the method long power(int, int) here.
    */
    long power(int n, int p) throws Exception {
        if(n==0 &amp;&amp; p==0) {
            throw new Exception("n and p should not be zero.");
        } else if(n&lt;0 || p&lt;0) {
            throw new Exception("n or p should not be negative.");
        } else {
            return (long)Math.pow(n, p);
        }
    }
}


Is there any way to use Exception handling in a better way in such questions? We have to perform this check in most of the questions. So I need to understand it clearly.
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);
}