我正在尝试在一段简单的C++代码上使用异常捕获机制,该代码故意除以 0:
#include <iostream>
using namespace std;
const int DefaultSize = 10;
int main()
{
int top = 90;
int bottom = 0;
cout << "top / 2 = " << (top/ 2) << endl;
cout << "top / 3 = " << (top/ 3) << endl;
try
{
cout << "top divided by bottom = ";
cout << (top / bottom) << endl;
}
catch(...)
{
cout << "something has gone wrong!" << endl;
}
cout << "Done." << endl;
return 0;
}
程序崩溃并且不执行捕获块 - 在 Eclipse 中,我收到一个标准错误:
0 [主要] CPP166 8964 cygwin_exception::open_stackdumpfile:将堆栈跟踪转储到 CPP166.exe.stackdump。在另一个 IDE NetBeans 中运行该程序,并执行了多次 clen 并重新构建,但没有积极的结果。请帮助我已经查看了相关答案,但我无法确定问题。
以零不是引发异常的事件之一 C++.
ISO 标准中列出的例外情况包括:
namespace std {
class logic_error;
class domain_error;
class invalid_argument;
class length_error;
class out_of_range;
class runtime_error;
class range_error;
class overflow_error;
class underflow_error;
}
你会认为overflow_error
是表示除以零的理想选择。
但C++03
和C++11
节5.6 /4
明确指出:
如果
/
或%
的第二个操作数为零,则行为未定义。
如果你想要一个例外,你必须自己编码,如下所示:
#include <stdexcept>
inline int intDiv (int num, int denom) {
if (denom == 0) throw std::overflow_error("DivByZero");
return num / denom;
}
并将您的呼叫从以下位置转换:
cout << (top / bottom) << endl;
自:
cout << intDiv(top, bottom) << endl;