对 std::runtime_error 与 std::logic_error 感到困惑 [英] Confused about std::runtime_error vs. std::logic_error

查看:21
本文介绍了对 std::runtime_error 与 std::logic_error 感到困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近看到,如果命令行输入不可解析,boost program_options 库会抛出一个 logic_error.这挑战了我关于 logic_errorruntime_error 的假设.

I recently saw that the boost program_options library throws a logic_error if the command-line input was un-parsable. That challenged my assumptions about logic_error vs. runtime_error.

我认为逻辑错误(logic_error 及其派生类)是由于内部未能遵守程序不变量而导致的问题,通常以内部 API 的非法参数的形式出现.从这个意义上说,它们在很大程度上等同于 ASSERT,但旨在用于已发布的代码(与通常不会编译为已发布代码的 ASSERT 不同.)它们在无法在调试/测试版本中集成单独的软件组件的情况下很有用或者失败的后果使得向用户提供有关无效不变条件的运行时反馈非常重要.

I assumed that logic errors (logic_error and its derived classes) were problems that resulted from internal failures to adhere to program invariants, often in the form of illegal arguments to internal API's. In that sense they are largely equivalent to ASSERT's, but meant to be used in released code (unlike ASSERT's which are not usually compiled into released code.) They are useful in situations where it is infeasible to integrate separate software components in debug/test builds or the consequences of a failure are such that it is important to give runtime feedback about the invalid invariant condition to the user.

同样,我认为 runtime_error 完全是由程序员控制之外的运行时条件引起的:I/O 错误、无效的用户输入等.

Similarly, I thought that runtime_errors resulted exclusively from runtime conditions outside of the control of the programmer: I/O errors, invalid user input, etc.

然而,program_options 显然被大量(主要是?)用作解析最终用户输入的手段,所以在我的心智模型下,它肯定会在输入错误的情况下抛出 runtime_error.

However, program_options is obviously heavily (primarily?) used as a means of parsing end-user input, so under my mental model it certainly should throw a runtime_error in the case of bad input.

我哪里出错了?你同意异常类型的 boost 模型吗?

Where am I going wrong? Do you agree with the boost model of exception typing?

推荐答案

在这种情况下,我认为(至少在大多数情况下)你是对的,但它是错的.该标准将 logic_error 描述为:

In this case, I think (at least for the most part) you're right and it's wrong. The standard describes logic_error as:

类 logic_error 定义了作为异常抛出的对象类型,以报告可能在程序执行之前检测到的错误,例如违反逻辑前提条件或类不变量.

The class logic_error defines the type of objects thrown as exceptions to report errors presumably detectable before the program executes, such as violations of logical preconditions or class invariants.

无法解析的命令行参数似乎不太适合.

A command line argument that can't be parsed doesn't seem to fit that very well.

相比之下,它将runtime_error描述为:

By contrast, it describes runtime_error as:

runtime_error 类定义了作为异常抛出的对象类型,以报告可能只有在程序执行时才能检测到的错误.

The class runtime_error defines the type of objects thrown as exceptions to report errors presumably detectable only when the program executes.

这似乎更合适.

这篇关于对 std::runtime_error 与 std::logic_error 感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆