4 comments

[ 2.0 ms ] story [ 23.2 ms ] thread
What is in your opinion the best way to return from a division by zero

  * Infinity
  * Throw Error
  * 0 
  * Something else
I wanted to submit this as an ask hn, and share the url that suggest the 0 answer, but I sort of failed
I don't think there is a universally best way. It rather depends on exactly what you're doing. The critical thing is that there is some unambiguous way to signal that an invalid mathematical operation occurred. As a default, I prefer to handle it by throwing an exception.

But really, I prefer to engineer the code such that divide-by-zero errors cannot occur. A divide-by-zero is an invalid operation better to be avoided entirely.

I believe this is the right answer: division by zero is dubious enough one wants to always special-case it; yes, sometimes 1/0=0 is the right answer but sometimes 1/9=∞ is better, or just display a blank indicating "N/A". You want an exception or, better still, a compiler that forces you to declare what to do each time 1/0 becomes possible in your code.
(comment deleted)