C++ stdexcept length_error Class
Example
Throw a length_error when a username is too long:
string username = "programmer_john_1990";
try {
if (username.length() > 12) {
throw length_error("The username can have at most 12 characters");
}
cout << "Welcome, " << username;
} catch (const length_error& e) {
cout << e.what();
}
Definition and Usage
A length_error reports that something would get longer than its maximum allowed length.
The library throws it too, for example when you ask a vector to reserve() room for more elements than it can ever store (more than max_size()).
The length_error class is defined in the <stdexcept> header file.
Syntax
throw length_error(message);
Catch it with catch (const length_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 length_error object. Its what() function returns the message. |
|---|
Related Pages
Read more about exceptions in our Exceptions Tutorial.