[java] 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!

This question is related to java exception math divide-by-zero

The answer is


Something like:

if(divisor == 0) {
  throw new ArithmeticException("Division by zero!");
}

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.

Define custom exception

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();

Throw ArithmeticException

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");

Do this:

if (denominator == 0) throw new ArithmeticException("denominator == 0");

ArithmeticException is the exception which is normally thrown when you divide by 0.


public class ZeroDivisionException extends ArithmeticException {
    // ...
}

if (denominator == 0) {
    throw new ZeroDivisionException();
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to exception

Connection Java-MySql : Public Key Retrieval is not allowed How to print an exception in Python 3? ASP.NET Core Web API exception handling Catching FULL exception message How to get exception message in Python properly What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean? what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean? Argument Exception "Item with Same Key has already been added" The given key was not present in the dictionary. Which key? sql try/catch rollback/commit - preventing erroneous commit after rollback

Examples related to math

How to do perspective fixing? How to pad a string with leading zeros in Python 3 How can I use "e" (Euler's number) and power operation in python 2.7 numpy max vs amax vs maximum Efficiently getting all divisors of a given number Using atan2 to find angle between two vectors How to calculate percentage when old value is ZERO Finding square root without using sqrt function? Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt? How do I get the total number of unique pairs of a set in the database?

Examples related to divide-by-zero

PHP Warning: Division by zero How do I catch a numpy warning like it's an exception (not just for testing)? How do I avoid the "#DIV/0!" error in Google docs spreadsheet? How should I throw a divide by zero exception in Java without actually dividing by zero?