Divide by Zero: Infinite, NaN, or Zero Division Error? [closed]-Collection of common programming errors

Floating point operations can detect several exceptional conditions and react in a couple of different ways:

  • Setting a status flag that can be later tested.
  • Immediately generating a trap.

The first mode of operation allows high performance, while the second mode allows immediate notification of possibly erronous operations.

IEEE 754 defines some sane values for the result of operations that raise exceptions (e.g: dividend finite nonzero number and divisor zero → correctly signed INFINITY; 0/0 → Quiet NaN).

The IEEE 754 intention with traps, is that there would be user mode handlers that could inspect the operation, the operands (for Invalid Operation and Divide by Zero exception) or result (for Overflow, Underflow and Inexact exceptions) and exception flags and return a new user-defined result.

In reality, some languages don’t even support accessing the exception status flags, let alone set trap handlers.

Even C provides very primitive support for trap handlers, C99 doesn’t even define a portable way to set trapping mode, requiring e.g: passing some implementation-defined value to fesetenv(). Implementations will typically raise a SIGFPE, and the user will typically need to access CPU-dependent state to implement a IEEE-754-like trap handler.

Originally posted 2013-11-09 23:11:49.