* Rui Maciel, on 30.05.2010 12:51:
Is there a C++ way to handle floating point exceptions?
If you mean "does the C++ standard support floating point exceptions" then the
answer is no, as it is for GUI, database, whatever. Arguably floating point
exceptions are in a more fundamental class than GUI functionality or database
functionality. But there you are: the only slight concession to the existence of
floating point exceptions is the somewhat unreliable information available via
std::numeric_limits (it's unreliable since one main compiler, g++, can be
configured to lie and AFAIK offers no way to detect whether it lies).
If you mean "are some ways of handling C++ floating point exceptions more in the
spirit of C++ than others" then the answer is yes.
Good C++ code assumes non-restartable synchronous exceptions and that exceptions
can be safely passed up through the call chain (which means e.g. using
destructors for cleanup, called RAII). So restartable exceptions would not be in
the spirit of C++, and you'd risk Undefined Behavior. Likewise, asynchronous
exceptions, exceptions occuring as if out of nowhere in the middle of some
operation designed not to throw, risks Undefined Behavior.
A simple way to deal with floating point errors is to assert that floating point
operations are IEEE 754, turn off floating point exceptions if they're not
already off, and detect NaN values. However, considering the g++ optimization
option I alluded to above there is AFAIK /no way/ to portably assert that the
operations conform to IEEE 754. You can assert that the bitlevel representation
is IEEE 754, but that doesn't help much.
A more practical way is to /assume/ that operations are IEEE 754, and document
this. Anyone using your code with non-IEEE 754 is screwed by own choice.
Then you can just detect NaNs at selected points and, if needed, throw ordinary
C++ exceptions, which are non-restartable and synchronous and safe.
Cheers & hth.,
- Alf