The header <stdexcept>
defines a couple of standard exceptions. However, I have troubles determining when to use which exception. Are there good guidelines to be found on-line? I try to illustrate my problem with an example:
A function takes the length of a (physical) vector and an angle (between 0 and pi) to return a new vector. If the angle is negative is that
std::invalid_argument
, as negative angles are invalid?std::logic_error
, as negative angles do not make sense in this case?std::out_of_range
, as negative angles are outside the allowed range for angles?std::domain_error
, as the mathematical function is not defined on negative angles.(In case anybody wonders: I am trying to transform coordinates in a triclinic simulation box, which are actually three lengths and three angles - see here if you are interested.)
The intentions for these exceptions:
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
, andstd::experimental::bad_optional_access
are derived fromstd::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.
Given that, I would rule out use of std::logic_error
and std::out_of_range
for your situation.
std::ivalid_argument
is less specific than std::domain_error
. Hence, my recommendation would be to use std::domain_error
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With