Search code examples
javaexceptionthrow

Java Type of Exception to Throw


I am trying to understand WHY to throw certain exceptions. What does it matter which one I choose to throw?

For example

//simple division method - a/b
public static double divide(double a, double b){
    if(b == 0)
        throw new IllegalArgumentException("b = 0");
    return a/b;
}

vs

//simple division method - a/b
public static double divide(double a, double b){
    if(b == 0)
        throw new IllegalArithmeticException("b = 0");
    return a/b;
}

(Apologies if there are errors in the code - I threw it together quickly. I'm not actually interested in the method itself.)

Does it matter which exception I choose? It seems like it could be anything - even if I used arrayIndexOutOfBoundsException, it would still stop the program and print what I want it to print.

Thanks for any help.


Solution

  • It's worth discussing what the difference is between a checked and an unchecked exception is, to hammer home a critical point of what exception to throw.

    Let's say that you're attempting to read a file, and for whatever reason, the file isn't found. Java has a convenient FileNotFoundException that you can use to explicitly inform that the file isn't found. It's also one of the exceptions which extend (through its hierarchy) Exception, meaning that if a method states that this exception is thrown, it must be dealt with either by catching it or declaring it to be thrown elsewhere.

    Then, there's the ArithmeticException, which is a runtime exception (it extends RuntimeException) - no methods need to declare this to be thrown, and you're not required to catch it explicitly, since this class of exceptions indicate an error in the code. It can come up, and in actuality, if anything were to try and catch a runtime exception, it'd look a little bit suspect.

    In the context of your problem, you're basically stomping over the natural throwing of the ArithmeticException by forewarning the user of valid input. It's likely acceptable to do something like this, but for this context, you actually don't need to throw anything yourself. If someone decides to pass b = 0 into the method, they'll get the ArithmeticException.

    There are existing conventions to follow based on exceptions - be as specific about the problem as possible, and offer a way to recover if appropriate - so in this scenario, if you had to throw a specific exception, I'd recommend IllegalArgumentException, since the argument b = 0 isn't acceptable when dividing or doing modulo. However, I'd also recommend that it be caught in a method outside of this instead, since the input is really suspect and it should be ideally sanitized before it makes its way to this method.