![]() |
VOOZH | about |
In C++, a part of the code that may throw exceptions is enclosed in try-and-catch blocks to handle them when they arise. However, floating-point errors in C++ do not throw exceptions by default and therefore cannot be handled directly using try-catch blocks. In this article, we will look at how floating-point errors behave in C++ and how they can be detected correctly.
Floating-point errors like division by zero cannot be caught by the try-catch block in C++. Such operations follow the IEEE-754 floating-point standard and result in special values such as inf or nan instead of throwing exceptions.
Result: inf
Explanation: Within the try block, a floating-point division by zero is performed. No exception is thrown in this case, so the catch block is never executed.According to the IEEE-754 standard, dividing a floating-point value by zero results in inf (infinity), which is printed directly from the try block.
In a similar way, floating-point conditions such as overflow, underflow, or invalid operations are not handled using try-catch blocks and must be detected explicitly using functions like std::isinf() or std::isnan().
Note: We can use the floating point environment from the standard library <cfenv> to detect floating-point exceptions, but functions like std::feenableexcept are not part of the C++ standard and are compiler-specific (for example, available as a GCC extension).