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.
Catching Floating Point Errors
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.
#include <iostream>
#include <stdexcept>
using namespace std;
int main()
{
try {
double result
= 1.0 / 0.0; // Attempting division by zero
cout << "Result: " << result << endl;
}
catch (const exception& e) {
cerr << "Exception caught: " << e.what() << endl;
}
return 0;
}
Output
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).