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

后端 未结 5 1024
鱼传尺愫
鱼传尺愫 2020-12-09 02:28

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

相关标签:
5条回答
  • 2020-12-09 02:45

    Do this:

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

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

    0 讨论(0)
  • 2020-12-09 02:51

    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");
    }
    
    0 讨论(0)
  • 2020-12-09 02:53

    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");
    
    0 讨论(0)
  • 2020-12-09 02:56

    Something like:

    if(divisor == 0) {
      throw new ArithmeticException("Division by zero!");
    }
    
    0 讨论(0)
  • 2020-12-09 03:02
    public class ZeroDivisionException extends ArithmeticException {
        // ...
    }
    
    if (denominator == 0) {
        throw new ZeroDivisionException();
    }
    
    0 讨论(0)
提交回复
热议问题