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

Program executed on Cygwin does not report a thrown exception

本文关键字:报告 抛出异常 程序 Cygwin 执行      更新时间:2023-10-16

当我运行如下所示的简单程序时,我在Cygwin和Ubuntu操作系统上得到不同的终端输出。

#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 %fn", input, result);
    return 0;
}

在Cygwin上,不像Ubuntu,我没有得到任何提示抛出异常的消息。原因是什么呢?是否有一些我需要下载Cygwin,以便它处理异常,因为它应该?

我使用Cygwin版本1.7.30与GCC 4.9.0。在Ubuntu上,我的版本是13.10,GCC 4.8.1。在这种情况下,我怀疑编译器的差异是否重要。

这种情况下没有定义行为-您依赖于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 %fn", input, result);
        return 0;
    }
    catch(...)
    {
        printf("Caught exception in main that wasn't handled...");
        return 10;
    }
}

一个很好的解决方案,正如Matt McNabb建议的那样,是"重命名main",并做这样的事情:

int actual_main() {
    const double input = -1;
    double result = square_root(input);
    printf("Square root of %f is %fn", input, result);
    return 0;
}
int main()
{
    try
    {
        return actual_main();
    }
    catch(std::exception e)
    {
         printf("Caught unhandled std:exception in main: %sn", e.what().c_str());
    }
    catch(...)
    {
         printf("Caught unhandled and unknown exception in main...n");
    }
    return 10;
}

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

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

你应该自己捕捉异常,或者使用在这个问题的答案中解释的东西

调试这类c++错误的一种方法是简单地用C重写它,然后将其翻译回c++。C语言更简单,所以把它翻译成C语言应该可以消除你的问题。