I am confused with how Scala handles division by zero. Here is a REPL code snippet.
scala> 1/0
java.lang.ArithmeticException: / by zero
... 33 elided
scala> 1.toDouble/0.toDouble
res1: Double = Infinity
scala> 0.0/0.0
res2: Double = NaN
scala> 0/0
java.lang.ArithmeticException: / by zero
... 33 elided
scala> 1.toInt/0.toInt
java.lang.ArithmeticException: / by zero
... 33 elided
As you can see in the above example, depending on how you divide by zero, you get one of the following:
This makes debugging quite challenging especially when dealing with data of unknown characteristics. What is the reasoning behind this approach, or even a better question, how to handle division by zero in a unified manner in Scala?
It's all down to the division by zero rules for various types.
0 / 0
is an integer division by zero (as both arguments are integer literals), and that is required to throw a java.lang.ArithmeticException
.
1.toDouble/0.toDouble
is a floating point division by zero with a positive numerator, and that is required to evaluate to +Infinity
.
0.0/0.0
is a floating point division by zero with a zero numerator, and that is required to evaluate to +NaN
.
The first is a Java and Scala convention, the other two are properties of IEEE754 floating point, which is what Java and Scala both use.