C++ Standard Library C++ STL Library

C++ <cfenv> - feraiseexcept() Function



The C++ <cfenv> feraiseexcept() function attempts to raise the floating-point exceptions specified by excepts. Programs calling this function shall ensure that pragma FENV_ACCESS is enabled for the call.

If one of the exceptions is FE_OVERFLOW or FE_UNDERFLOW, this function may additionally raise FE_INEXACT. If more than one exception is specified, the order in which the exceptions are raised is unspecified, except that FE_OVERFLOW and FE_UNDERFLOW are always raised before FE_INEXACT.

Syntax

int feraiseexcept (int excepts);

Parameters

excepts

Specify bitmask listing the floating-point exception flags to raise.

MacrosDescription
FE_DIVBYZERO Pole error exception occurred in an earlier floating-point operation.
FE_INEXACT Inexact result exception occurred in an earlier floating-point operation (rounding was necessary to store the result).
FE_INVALID Invalid argument exception occurred (domain error occurred) in an earlier floating-point operation.
FE_OVERFLOW Overflow range error exception occurred in an earlier floating-point operation (result was too large to be representable).
FE_UNDERFLOW Underflow range error exception occurred in an earlier floating-point operation (result was subnormal with a loss of precision).
FE_ALL_EXCEPT Bitwise OR of all supported floating-point exceptions.

Certain library implementations may define additional macro constants in <cfenv> to identify additional floating-point exceptions (with their corresponding macros also beginning with FE_).

Return Value

Returns 0 if all exceptions in excepts were successfully cleared or if excepts is zero. Returns a non-zero value otherwise.

Exception

This function never throws exceptions.

Example:

In the example below, the feraiseexcept() function is used to raise floating-point exceptions.

#include <iostream>
#include <cfenv>
#include <cmath>

#pragma STDC FENV_ACCESS ON

using namespace std;

void FE_Exceptions_Message(void) {
  cout<<"Exceptions raised:";
  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";
  
  feclearexcept(FE_ALL_EXCEPT);
  cout<<endl;
}

//function which raises exception 
//when argument is less than zero
void MyFunction(double x) {
  //raise exception
  if(x < 0.0)
    feraiseexcept(FE_INEXACT | FE_INVALID);
  cout<<"MyFunction() successfully raised exceptions.\n";
}

int main (){
  MyFunction(-1.0);
  FE_Exceptions_Message();
  return 0;
}

The output of the above code will be:

MyFunction() successfully raised exceptions.
Exceptions raised: FE_INEXACT FE_INVALID

❮ C++ <cfenv> Library