C++ stdexcept invalid_argument Class
Example
Throw an invalid_argument when an age is negative:
int age = -5;
try {
if (age < 0) {
throw invalid_argument("Age cannot be negative");
}
cout << "Age is: " << age;
} catch (const invalid_argument& e) {
cout << e.what();
}
Definition and Usage
An invalid_argument reports that a value is not valid, because it breaks a rule, like a negative age.
The name comes from functions: an argument is a value that you give to a function. It is common to throw invalid_argument at the start of a function, when a value that the function gets is not valid.
The invalid_argument class is defined in the <stdexcept> header file.
Tip: The stoi() function throws an invalid_argument when the string does not start with a number, like stoi("hello"). Learn more in the Convert Strings and Numbers chapter.
Syntax
throw invalid_argument(message);
Catch it with catch (const invalid_argument& 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 invalid_argument object. Its what() function returns the message. |
|---|
Related Pages
Read more about exceptions in our Exceptions Tutorial.