try() 和 catch() 不起作用;程序崩溃,从不执行 catch() 块
The try() and catch() are not working; The program crashes and never executes the catch() block
我正在尝试在一段简单的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;
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- C++,系统无法执行指定的程序
- 使用C++中的模板和运算符重载执行矩阵运算
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 执行函数时导致崩溃的变量
- 无论条件是否为true,if总是在c++中执行
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 在C++中对T*类型执行std::move的意外行为
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如何在没有信号的情况下从C++执行QML插槽
- 为什么catch中的代码没有被执行
- 抛出多个异常时,catch 块执行的顺序是什么,为什么?
- 将在 CATCH 块之后执行代码
- 为什么我的 catch 代码没有被执行?
- 为什么我的程序不执行第二个catch块
- 当错误存在时,为什么我的程序不执行第二个catch块
- try() 和 catch() 不起作用;程序崩溃,从不执行 catch() 块
- 在try-catch语句中的try块和所有catch时钟的末尾执行相同的操作
- c++程序在不执行catch块的情况下终止
- 扩展 std::exception 类:程序不会执行适当的 catch handler