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

前端之家收集整理的这篇文章主要介绍了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.f2er.com/c/239439.html

猜你在找的C&C++相关文章