gpt4 book ai didi

C++ 什么时候使用哪个(标准)异常?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:26:43 24 4
gpt4 key购买 nike

header <stdexcept>定义了几个标准异常。但是,我无法确定何时使用哪个异常。是否可以在线找到好的指南?我试着用一个例子来说明我的问题:

函数采用(物理) vector 的长度和角度(介于 0 和 pi 之间)返回一个新 vector 。如果角度是负的就是

  1. A std::invalid_argument , 因为负角无效?
  2. A std::logic_error , 因为负角在这种情况下没有意义?
  3. A std::out_of_range , 因为负角超出了允许的角度范围?
  4. A std::domain_error ,因为数学函数没有在负角上定义。
  5. 或者我应该定义一个自定义异常吗?

(如果有人想知道:我正在尝试转换三斜模拟箱中的坐标,实际上是三个长度和三个角度 - 如果您有兴趣,请参阅 here。)

最佳答案

这些异常(exception)的意图:

std::invalid_argument :

Defines a type of object to be thrown as exception. It reports errors that arise because an argument value has not been accepted.

std::logic_error :

Defines a type of object to be thrown as exception. It reports errors that are a consequence of faulty logic within the program such as violating logical preconditions or class invariants and may be preventable.

No standard library components throw this exception directly, but the exception types std::invalid_argument, std::domain_error, std::length_error, std::out_of_range, std::future_error, and std::experimental::bad_optional_access are derived from std::logic_error.

std::out_of_range :

Defines a type of object to be thrown as exception. It reports errors that are consequence of attempt to access elements out of defined range.

std::domain_error :

Defines a type of object to be thrown as exception. It may be used by the implementation to report domain errors, that is, situations where the inputs are outside of the domain on which an operation is defined.


鉴于此,我会排除使用 std::logic_errorstd::out_of_range 的情况。

std::valid_argument 不如 std::domain_error 具体。因此,我的建议是使用 std::domain_error

关于C++ 什么时候使用哪个(标准)异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38733270/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com