C ++ When to use which (standard) exception?

The <stdexcept> defines a pair of standard exceptions. However, I have problems determining when to use which exception. Are there any good recommendations you can find online? I will try to illustrate my problem with an example:

The function takes the length of the (physical) vector and the angle (between 0 and pi) to return a new vector. If the angle is negative, then

  • A std::invalid_argument , since negative angles are not valid?
  • A std::logic_error , since negative angles do not make sense in this case?
  • A std::out_of_range , since negative angles are outside the allowed range for angles?
  • A std::domain_error , because the mathematical function is not defined at negative angles.
  • Or should I define a custom exception?

(In case someone wonders: I'm trying to convert the coordinates into a triclinic simulation box, which are actually three lengths and three angles - see here if you are interested.)

+6
source share
1 answer

Prerequisites for these exceptions:

std::invalid_argument :

Defines the type of object to be excluded. It reports errors that occur because the argument value has not been accepted.

std::logic_error :

Defines the type of object to be excluded. It reports errors that result from erroneous logic within the program, for example, violations of logical preconditions or class invariants and can be prevented.

No standard library components send 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 the type of object to be excluded. It reports errors that result from trying to access items from a specific range.

std::domain_error :

Defines the type of object to be excluded. It can be used in the implementation for reporting domain errors, that is, in situations where the inputs are outside the domain on which the operation is defined.


Given this, I would eliminate the use of std::logic_error and std::out_of_range for your situation.

std::ivalid_argument less specific than std::domain_error . Therefore, my recommendation would be to use std::domain_error .

+7
source

All Articles