微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

标题< 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.

原文地址:https://www.jb51.cc/c/239439.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐