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.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...