c++ - 运行时错误和逻辑错误的区别

标签 c++ runtime-error

我已经学习 C++ 两个月了,现在我正在学习我的书(Programming Principles and Practice using C++)中关于错误的章节。但是在研究了第一页之后我有一个问题:运行时错误和逻辑错误有什么区别?根据我的书,运行时错误是在运行时通过检查发现的错误,我们可以进一步将运行时错误分类为:

  • 硬件错误/操作系统错误
  • 图书馆检测到的错误
  • 用户代码检测到的错误(什么是用户代码?)

而逻辑错误只是程序员在寻找错误结果的原因时发现的错误。

我以为我已经理解了这种差异,但后来作者提供的一个例子让我产生了疑问。这是示例:

#include "std_lib_facilities.h"

int area(int lenght, int width) // calculate area of rectangle 
{
    return lenght * width; 
}

int framed_area(int x, int y) // calculate area within frame 
{
    return area(x - 2, y - 2); 
}

int main()
{
    int x = -1;
    int y = 2; 
    int z = 4; 
    int area1 = area(x, y); 
    int area2 = framed_area(1, z); 
    int area3 = framed_area(y, z); 
    double ratio = double(area1) / area3; 
}

以下是作者对这个例子的简要说明:

the calls of the function area() and framed_area() lead to negative values, representing areas, being assigned to area1 and area2. Should we accept such erroneous results? But before answering these question look at the calculation of ratio, in the calculation of ratio area3 will be 0 and the division with 0 will lead to hardware-detected error that terminates the program with some cryptic message. This is the kind of error that you, or your user, will have to deal with if you don't detect and deal sensibly with runtime errors.

这里我不明白的是,为什么一个负值作为参数用于计算面积的函数会被视为运行时错误,这不只是逻辑错误吗?我认为运行时错误只是错误,例如将数字除以 0 和其他特殊情况。我错了还是我只是误会了什么? 逻辑错误和运行时错误之间的真正区别是什么?您能给我举一些小例子吗?

最佳答案

运行时错误可能会合法地发生:例如一些包含垃圾数据的文件,或者一些错误的人为输入,或者一些资源不足(没有更多的内存,磁盘空间已满,硬件损坏,网络连接失败)。

根据定义,逻辑错误(或失败的 assert ....)总是是程序中某些错误的症状,例如用于二分法访问的假设排序的数组恰好是未排序的。

参见 documentation of <stdexcept> header :

std::logic_error: This class defines the type of objects thrown as exceptions to report errors in the internal logical of the program, such as violation of logical preconditions or class invariants.

std::runtime_error: This class defines the type of objects thrown as exceptions to report errors that can only be detected during runtime.

我相信 std::logic_error内部逻辑是一个打字错误,我将其理解为(程序的)内部逻辑,但我的母语不是英语。

如果您将程序规范形式化(例如,在 Frama C 的帮助下使用 ACSL),您可能会发现(并可能纠正)逻辑错误;但你应该关心运行时错误。但是您也可能在规范中存在错误。

了解 Ariane 5 flight 501 failure .并查看J.Pitrat's blog获得一些其他观点。

关于c++ - 运行时错误和逻辑错误的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28095673/

相关文章:

java - Windows 7 上的 JVM 核心转储文件位于何处?

c++ - 使用 extern 的显式实例化声明

c++ - 在 ubuntu 中编译 GLUT 时出错

c++ - 在没有lambda函数的情况下使用C++中的另一个 vector 对 vector 进行排序

ruby-on-rails - Rails + Redis 订阅返回错误

java - 如何使用 SQL 浏览图像并将其保存到 Oracle DB 中?

c++ - 在 C++ 中重载 operator+

java - 如何创建 bash 文件以使用 VM 参数启动 Java 程序

vba - “On error resume next”处于事件状态时,不会引发错误(运行时错误5)

compilation - 错误:找不到或加载主类Hello.class