C++ stdexcept out_of_range Class
Example
Throw an out_of_range when an index is too big:
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
int index = 6;
try {
if (index > 3) {
throw out_of_range("The index is too big");
}
cout << cars[index];
} catch (const out_of_range& e) {
cout << e.what();
}
Definition and Usage
An out_of_range reports that a value is outside the allowed range, like an index that is larger than the last position of an array.
In the example, the array has 4 elements, so the last index is 3. The program checks the index before it uses it, because cars[6] does not exist.
The out_of_range class is defined in the <stdexcept> header file.
Note: Library functions also throw out_of_range, like at() of a vector and at() of a string, when the index is too big. The message that what() returns for them is different for each compiler.
Syntax
throw out_of_range(message);
Catch it with catch (const out_of_range& 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: | An out_of_range object. Its what() function returns the message. |
|---|
Related Pages
Read more about exceptions in our Exceptions Tutorial.