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

后端 未结 5 1034
鱼传尺愫
鱼传尺愫 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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");
    }
    

提交回复
热议问题