加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C何时使用哪个(标准)例外?

发布时间:2020-12-16 04:57:38 所属栏目:百科 来源:网络整理
导读:标题 stdexcept定义了几个标准异常.但是,我在确定何时使用哪个例外时遇到了麻烦.是否有良好的在线指南?我试着通过一个例子说明我的问题: 函数采用(物理)矢量的长度和角度(在0和pi之间)来返回新的矢量.如果角度是负的那就是 一个std :: invalid_argument,因
标题< stdexcept>定义了几个标准异常.但是,我在确定何时使用哪个例外时遇到了麻烦.是否有良好的在线指南?我试着通过一个例子说明我的问题:

函数采用(物理)矢量的长度和角度(在0和pi之间)来返回新的矢量.如果角度是负的那就是

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

(如果有人想知道:我试图在三斜模拟框中变换坐标,实际上是三个长度和三个角度 – 如果你有兴趣,请参见here.)

解决方法

这些例外的意图:

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_error和std :: out_of_range来处理你的情况.

std :: ivalid_argument的特定性不如std :: domain_error.因此,我的建议是使用std :: domain_error.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读