Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

exception

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

  1. A std::invalid_argument, as negative angles are invalid?
  2. A std::logic_error, as negative angles do not make sense in this case?
  3. A std::out_of_range, as negative angles are outside the allowed range for angles?
  4. A std::domain_error, as the mathematical function is not defined on negative angles.
  5. Or should I define a custom exception?

(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.)

like image 733
Julian Helfferich Avatar asked Aug 03 '16 02:08

Julian Helfferich


1 Answers

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, 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.


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.

like image 160
R Sahu Avatar answered Nov 03 '22 13:11

R Sahu