Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I throw a divide by zero exception in Java without actually dividing by zero?

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) is done. The problem with this is that a divide by zero could occur on the I2C device, so a divide by zero error needs to be checked for. Ideally, exactly the same thing would happen if the dividing were done by the java code.

At the moment, I've bodged an unused variable that does the division, but I'm worried it'll get optimized out:

public void setKp(int numerator, int divisor) {     int zeroCheck = numerator / divisor;     //... doesn't use zeroCheck } 

Surely there's a better way!

like image 352
Eric Avatar asked Nov 01 '09 18:11

Eric


People also ask

What can I do instead of dividing by zero?

In elementary algebra, another way of looking at division by zero is that division can always be checked using multiplication.

What happens if you divide 0 by 0 in Java?

Dividing by zero is an operation that has no meaning in ordinary arithmetic and is, therefore, undefined.

Which exception is thrown when we divide by zero?

If you divide int by 0, then JVM will throw Arithmetic Exception.


1 Answers

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"); } 
like image 105
Joren Avatar answered Oct 06 '22 04:10

Joren