C++ stdexcept range_error Class
Example
Throw a range_error when a number is too big to fit in a short:
int number = 100000;
try {
if (number > SHRT_MAX) {
throw range_error("The number is too big for a short");
}
short result = number;
cout << result;
} catch (const range_error& e) {
cout << e.what();
}
Definition and Usage
A range_error reports that a result is outside the range of values that its data type can store.
In the example, the program wants to store an int in a short (a smaller integer type). SHRT_MAX (from <climits>) is the largest value a short can store, and 100000 is larger.
The range_error class is defined in the <stdexcept> header file.
Tip: For a calculation with a result that is too big, use overflow_error. For a result that is too close to 0, use underflow_error.
Syntax
throw range_error(message);
Catch it with catch (const range_error& e), and use e.what() to get the message.
Parameter Values
| Parameter | Description |
|---|---|
| message | Required. A text that describes the error, as a string or as text in double quotes. what() returns this text. |
Technical Details
| Returns: | A range_error object. Its what() function returns the message. |
|---|
Related Pages
Read more about exceptions in our Exceptions Tutorial.