I have an I2C device that wants two inputs: a denominator and a numerator. Both are written to separate addresses, so no actual calculation (numerator/denominator
Do this:
if (denominator == 0) throw new ArithmeticException("denominator == 0");
ArithmeticException is the exception which is normally thrown when you divide by 0.
You should not throw an ArithmeticException. Since the error is in the supplied arguments, throw an IllegalArgumentException
. As the documentation says:
Thrown to indicate that a method has been passed an illegal or inappropriate argument.
Which is exactly what is going on here.
if (divisor == 0) {
throw new IllegalArgumentException("Argument 'divisor' is 0");
}
There are two ways you could do this. Either create your own custom exception class to represent a divide by zero error or throw the same type of exception the java runtime would throw in this situation.
public class DivideByZeroException() extends ArithmeticException {
}
Then in your code you would check for a divide by zero and throw this exception:
if (divisor == 0) throw new DivideByZeroException();
Add to your code the check for a divide by zero and throw an arithmetic exception:
if (divisor == 0) throw new java.lang.ArithmeticException("/ by zero");
Additionally, you could consider throwing an illegal argument exception since a divisor of zero is an incorrect argument to pass to your setKp() method:
if (divisor == 0) throw new java.lang.IllegalArgumentException("divisor == 0");
Something like:
if(divisor == 0) {
throw new ArithmeticException("Division by zero!");
}
public class ZeroDivisionException extends ArithmeticException {
// ...
}
if (denominator == 0) {
throw new ZeroDivisionException();
}