当我运行如下所示的简单程序时,我在 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 %f\n", input, result);
return 0;
}
在 Cygwin 上,与 Ubuntu 不同,我没有收到任何表明抛出异常的消息。这可能是什么原因?是否需要为 Cygwin 下载一些东西,以便它按预期处理异常?
我在 GCC 4.9.0 中使用 Cygwin 1.7.30 版。在 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 %f\n", 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 %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;
}
请注意,我们返回一个不同于零的值来表示“失败”——我预计至少 Cygwin 已经这样做了。
关于c++ - 在 Cygwin 上执行的程序不报告抛出的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24402412/