C++

Floating Point Exception C++ Why and what is it?

Floating-point exception occurs when a software tries to perform an improper operation on a numerical number. This type of exception occurs when a user attempts to execute invalid operations, such as division by zero, division of a negative number by an even number, taking the square root of a negative number, or overflow of a calculation that exceeds the limit of the double data type.

In C++, the “SIGFPE” signal handler handles the floating point exceptions (FPEs). When a user attempts to carry out the mentioned tasks, this signal handler is called. Once the signal handler has intervened, it prints an error message to standard output and halts the program.

Why Do Floating-Point Exceptions Occur?

Floating point exceptions can occur due to programming errors or when a program attempts to process a value that is out of specification. For example, if a program tries to divide an integer by zero, or if a program tries to take the square root of a negative number, a floating point exception will occur. Furthermore, some floating-point exceptions can occur due to processor misdetections.

Many factors, such as inappropriate operation, underflow, overflow, division by zero, and accuracy, might result in a floating-point exception. We will cover these arguments one by one in this section.

1: Illegal Operation

When a user forgets to express an operation or the operation has no mathematical value, the program fails to execute due to an invalid operation. This includes calculations such as the square root and logarithm of negative numbers, for instance. Although it is possible to take the square root of a negative number when dealing with complex numbers, there is no computer-based mechanism to express this.

Additionally, an incorrect operation will result if a software executes a floating-point operation on an integer-only location. This is due to a mismatch between the operation you are attempting to carry out on the data (floating-point operation) and the stored data (integer).

2: Zero division

A floating-point exception is thrown if you attempt to divide an integer by zero. The same thing occurs when you attempt to divide by NaN or infinity. Here are some examples: 1/0, log(0).

3: Overflow

When an operation returns a value that is outside of its expected range, an overflow exception happens. The value is either more or lower than the smallest representable value, according to this statement.

4: Underflow

Underflow happens when a calculation yields a result that is less than what a data type can hold.

5: Inexact

When the outcome of an operation differs from what was anticipated, this is known as an inexact exception. When the operation is performed with unbound precision and an exponent range, this occurs.

In some cases, such situations can be handled gracefully. For example, when a program attempts to divide a number by zero, it is generally preferable to return an error message and gracefully terminate the program instead of allowing the program to crash.

#include <iostream>

#include <stdexcept>

using namespace std;

float Div(float num, float den)

{

    if (den == 0) {

       throw runtime_error("Math error: Attempted to divide by 0\n");

    }

    return (num / den);

}

int main()

{

    float num, denom, result;

    num = 10;

    denom = 0;

    try {

        result = Div(num, denom);

            cout << "The quotient is " << result << endl;

    }

    catch (runtime_error& e) {

      cout << "Exception occurred" << endl << e.what();

    }

}

In this code, the Div function is called by the try block inside of main. If the denom is not equal to zero, the Div function returns the quotient; if it is, a runtime error exception is thrown. Before calling the what function with the runtime error object e, the catch block intercepts this exception and prints the text “Error occurred”. It is used to identify the exception. The class Standard exception, which is described in the stdexcept header file, has a virtual function called what(). The message “Math error: Attempted to divide by 0” is printed as a result.

Output

To prevent floating point exceptions in C++, it is essential to check all the parameters passed to functions, to use appropriate formats and to explicitly test divisors for zero values. In addition, when using double data types, it is important to enlarge the range of the data type if the program requires larger arithmetic results.

Conclusion

Floating point exceptions in C++ are caused by invalid operations on numerical values and can affect the program’s ability to execute correctly. To avoid such errors, it is important to check all the parameters passed to functions and to use the appropriate data types. Furthermore, it is beneficial to catch floating point exceptions.

About the author

Hiba Shafqat

I am a Computer Science student and a committed technical writer by choice. It is a great pleasure to share my knowledge with the world in which I have academic expertise.