在Cygwin上执行的程序没有报告抛出异常
Program executed on Cygwin does not report a thrown exception
当我运行如下所示的简单程序时,我在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语言应该可以消除你的问题。
相关文章:
- 从构造函数抛出异常时如何克服内存泄漏
- 函数如何通知用户它基于函数原型抛出异常?
- 在缺少函数重载时抛出异常,并带有 std::variant 而不是编译时错误
- VisualStudios 会抛出异常,而代码块不会 [C++]
- 如果不包含 pthread,为什么 GCC 的线程标准库实现会抛出异常?
- ZMQ::send() 抛出异常并终止 QNX 进程.为什么以及如何从中恢复?
- new(std::nothrow) int[n] 抛出异常
- 为什么g_object_set抛出异常(vcruntime140.dll)?
- 你能防止 std::regex 在无效表达式上抛出异常吗?
- C++子线程抛出异常
- 我们应该在抛出异常之前取消分配内存吗
- 有没有一种方法可以让OpenCLC++绑定为所有错误抛出异常
- 为什么访问模板化变体作为返回值抛出异常
- 如何实现,错误分配中止而不是抛出异常
- std::p riority_queue::p op什么时候会抛出异常
- 在0x5914F3BE抛出异常(基于.dll)
- std::vector 默认构造函数可以抛出异常吗?
- 挂钩创建文件抛出异常:读取访问冲突
- getaddrinfo 抛出异常
- 在Cygwin上执行的程序没有报告抛出异常