C++ fetestexcept()

The fetestexcept() function in C++ determines which of the specified subset of the floating point exceptions are currently set.

The fetestexcept() function is defined in <cfenv> header file.

fetestexcept() prototype

int fetestexcept( int excepts );

The fetestexcept() function tests whether the floating point exception specified by excepts are currently set. The argument excepts is a bitwise OR of the floating point exception macros.


fetestexcept() Parameters

  • excepts: Bitmask listing the exception flags to test.

fetestexcept() Return value

  • Bitwise OR of the floating-point exception macros that are both included in excepts and correspond to floating-point exceptions currently set.

Example: How fetestexcept() function works?

#include <iostream>
#include <cmath>
#include <cfenv>
#pragma STDC FENV_ACCESS ON
using namespace std;

void print_exceptions()
{
	cout << "Raised exceptions: ";
	if(fetestexcept(FE_ALL_EXCEPT))
	{
		if(fetestexcept(FE_DIVBYZERO))
			cout << "FE_DIVBYZERO ";
		if(fetestexcept(FE_INEXACT))
			cout << "FE_INEXACT ";
		if(fetestexcept(FE_INVALID))
			cout << "FE_INVALID ";
		if(fetestexcept(FE_OVERFLOW))
			cout << "FE_OVERFLOW ";
		if(fetestexcept(FE_UNDERFLOW))
			cout << "FE_UNDERFLOW ";
	}
	else
		cout << "None";

	cout << endl;
}

int main(void)
{
	print_exceptions();
	
	feraiseexcept(FE_INVALID|FE_DIVBYZERO);
	print_exceptions();

	feclearexcept(FE_ALL_EXCEPT);
	print_exceptions();
	
	return 0;
}

When you run the program, the output will be:

Raised exceptions: None
Raised exceptions: FE_DIVBYZERO FE_INVALID
Raised exceptions: None