在Cygwin上执行的程序不报告抛出的异常

use*_*874 4 c++ ubuntu gcc cygwin outofrangeexception

当我运行下面显示的简单程序时,我在Cygwin和Ubuntu OS上得到不同的终端输出.

#include    <cstdio>
#include    <stdexcept>
#include    <cmath>

using namespace std;

double square_root(double x)
{
    if (x < 0)
        throw out_of_range("x<0");

    return sqrt(x);
}

int main() {
    const double input = -1;
    double result = square_root(input);
    printf("Square root of %f is %f\n", input, result);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在Cygwin上,与Ubuntu不同,我没有收到任何表明抛出异常的消息.可能是什么原因?我是否需要为Cygwin下载一些内容,以便它能够处理异常情况?

我使用Cygwin版本1.7.30和GCC 4.9.0.在Ubuntu上,我有GCC 4.8.1版本13.10.我怀疑在这种情况下编译器的差异很重要.

Mat*_*son 6

在这种情况下没有定义行为 - 你依靠C++运行时的"善意"来为"你没有捕获异常"发出一些文本,Linux的glibc确实做了,显然Cygwin做了不.

相反,将主代码包装在一个try/catch处理throw.

int main() {
    try
    {
        const double input = -1;
        double result = square_root(input);
        printf("Square root of %f is %f\n", input, result);
        return 0;
    }
    catch(...)
    {
        printf("Caught exception in main that wasn't handled...");
        return 10;
    }
}
Run Code Online (Sandbox Code Playgroud)

Matt McNabb建议的一个很好的解决方案是"重命名主要",并做一些像这样的事情:

int actual_main() {
    const double input = -1;
    double result = square_root(input);
    printf("Square root of %f is %f\n", input, result);
    return 0;
}

int main()
{
    try
    {
        return actual_main();
    }
    catch(std::exception e)
    {
         printf("Caught unhandled std:exception in main: %s\n", e.what().c_str());
    }
    catch(...)
    {
         printf("Caught unhandled and unknown exception in main...\n");
    }
    return 10;
}
Run Code Online (Sandbox Code Playgroud)

请注意,我们返回一个不同于零的值来表示"失败" - 我希望至少Cygwin已经这样做了.


Axe*_*xel 4

由于您没有捕获异常,因此行为取决于实现/运行时。Linux 和 cygwin 的实现方式似乎不同。

您应该自己捕获异常,或者使用问题的答案中所解释的内容。