Differences between out_of_range, range_error and over / underflow_error?

Can someone explain what the differences between range_error , out_of_range and the pair of overflow_error and underflow_error are when I should use them? It seems they are all the same.

According to cppreference.com :

  • out_of_range : it reports errors that result from trying to access elements from a specific range.
  • range_error : it reports errors that occur because the floating point value cannot be represented in some calculations because it is too large or too small. If the value is an integral type, use std::underflow_error or std::overflow_error .
  • overflow_error : it reports errors that occur because the integer value cannot be represented in some calculation, because it has too much positive value.

In particular, I have a function,

 template<typename T> void write_integer(const T &n) { if(n < 0) { throw ??? } if(some_limit < n) { throw ??? } 

Where T is an integral type; the function does some border checking on n to see if it is in a certain range; if it is not, I would like to make some kind of exception. I am confused because:

  • out_of_range sounds like for indexing and checking the bounds of an array, which I am not doing.
  • range_error look like a float? (But why, in C ++?)
  • underflow_error and overflow_error ? Do they really fit?
+6
source share
2 answers

From the standard:

range_error : The range_error class defines the type of objects that were selected as exceptions for reporting range errors in internal calculations .

out_of_range : the out_of_range class defines the type of objects created as exceptions for reporting the value of an argument not in the expected range .

overflow_error : the overflow_error class defines the type of objects that were selected as exceptions for an arithmetic overflow error message.

underflow_error : the underflow_error class defines the type of objects created as exceptions for reporting an arithmetic error of a lower stream .

For your function, out_of_range most appropriate.

+3
source

I did not think about it much, but my recommendations look like this:

  • out_of_range , when my abstraction can be considered as a series of buckets or boxes (discrete), and I asked for a nonexistent bucket or pit. The main example is a request for the fourth element of a three-element array (slots in an array can be considered as buckets).

  • range_error , when the requested operation does not take into account the mathematical meaning in the area in question (for example, the square root of a negative number when working with a real domain).

  • overflow_error and underflow_error when the result exceeds the capacity of the base type. For example: an integer greater than what int can hold.

+2
source

All Articles