Search code examples
javaexceptionif-statementtry-catchthrow

Regarding try-catch


I am currently taking a introductory course in Java and this is regarding try-catch method. When I type this my System.out.println statement keeps repeating endlessly. Here is my code:

public static double exp(double b, int c) {
    if (c == 0) {
        return 1;
    }

    // c > 0
    if (c % 2 == 0) {
        return exp(b*b, c / 2);
    }
    if (c<0){
        try{
        throw new ArithmeticException();
        }
        catch (ArithmeticException e) {
            System.out.println("yadonegoofed");
        }
    }

    // c is odd and > 0
    return b * exp(b, c-1);
}

Solution

  • if (c<0){
        try{
        throw new ArithmeticException();
        }
        catch (ArithmeticException e) {
            System.out.println("yadonegoofed");
        }
    }
    
    // c is odd and > 0
    return b * exp(b, c-1);
    

    Your comment c is odd and > 0 is incorrect -- you never actually terminated the function with the exception. You threw it, you immediately caught it, and then continued to execute the recursive function. Eventually, when you hit wraparound, it'll be a positive number again, and the errors won't happen. (It's about two billion iterations away -- don't wait.)

    I would not use an exception here -- you just need to terminate the recursion. I'd check for negative input before checking for 0, and throw the exception there, and catch the exception in the caller.

    In pseudo-code:

    exp(double b, int c) {
        if (c < 0)
            throw new Exception("C cannot be negative");
        } else if (c % 2 == 0) {
            return exp(b*b, c / 2);
        } else {
            /* and so forth */
        }
    }