Open In App

How to Catch Floating Point Errors in C++?

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, a part of the code that may throw exceptions is enclosed in try-and-catch blocks to handle them when they arise. We can also use try…catch to catch floating point errors but it involves a bit different approach in comparison to catching standard exceptions. In this article, we will look at how to use try catch to catch floating-point exceptions in C++.

Catching Floating Point Errors

Floating-point errors like division by zero can be caught by the try-catch block in C++. We need to include the division code in the try block and catch any exception in the corresponding catch block.

C++ Program to Catch Floating Point Error

C++




// C++ program to handle division by zero exception
  
#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 division by zero is tried in the above example. The exception will be caught and handled by the catch block and it returns inf. Although more specialized exception types may be used if necessary, the std::exception type is used to capture common exceptions only.

In similar way, we can handle other floating point exceptions such as overflow, underflow, etc.

Note: We can use the floating point environment from the standard library <cfenv> to check for floating point exceptions but the function used (std::feenableexcept) is not part of the C++ standard it’s a GCC extension and may not be available on all platforms.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads