Scala division by zero yields different results

Viewed 2536

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:

  • "java.lang.ArithmeticException: / by zero"
  • "Double = NaN"
  • "Double = Infinity"

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?

3 Answers
Related