如何使用try-catch捕捉浮点数错误?

How to use try-catch to catch floating point errors?

#include <iostream>
#include <float.h>
#pragma fenv_access (on)
int main(int, char**argv)
{
    unsigned int fp_control_word;
    _controlfp_s(&fp_control_word, 0, 0);
    const unsigned int new_fp_control_word = fp_control_word | _EM_INVALID | _EM_DENORMAL
        | _EM_ZERODIVIDE | _EM_OVERFLOW | _EM_UNDERFLOW | _EM_INEXACT;
    _controlfp_s(&fp_control_word, new_fp_control_word, _MCW_EM);
   try
   {    std::cout << std::atof(argv[1]) / std::atof(argv[2]) << std::endl;
   } catch (...)
   {    std::cout << "caught exception" << std::endl;
   }

}

我记得可以使用 try-catch 块捕获 windows 上的内存访问错误。

已有一个关于此主题的问题。但它已有 10 年历史,提供的代码不会导致异常,但会打印 NAN。

我一直对使用此功能以一种很好的方式中止某些数字代码感到好奇。动机是立即中止一些非常复杂的代码,如果此代码中的任何地方发生浮点异常,而不是继续使用 NAN 结果评估其余代码——这相当慢而且无论如何都没有意义。

拜托:我不在乎这是否不受 C++ 标准支持!

问题是,如何将此代码 运行 放入 catch 块中——例如通过使用命令行参数 0.0 0.0!

对我来说,它总是打印出 NAN。

需要使用哪些编译器选项?

或者是否需要更改代码?

如果在 try 块中引发 nullptr 取消引用,那么将在 catch 块中结束。但不是为了除以零。 需要使用编译器选项 /EHa 来启用结构化异常处理。

感谢 https://whosebug.com/users/17034/hans-passant 提供解决方案。

工作代码来了:

#include <iostream>
#include <float.h>
#pragma fenv_access (on)
int main(int, char**argv)
{
    unsigned int fp_control_word;
    _controlfp_s(&fp_control_word, 0, _MCW_EM);
    const unsigned int new_fp_control_word = fp_control_word & ~(_EM_INVALID
        | _EM_DENORMAL | _EM_ZERODIVIDE | _EM_OVERFLOW | _EM_UNDERFLOW | _EM_INEXACT);
    _controlfp_s(&fp_control_word, new_fp_control_word, _MCW_EM);
    try
    {   std::cout << std::atof(argv[1]) / std::atof(argv[2]) << std::endl;
    } catch (...)
    {   std::cout << "caught exception" << std::endl;
    }
}