C++ stdexcept logic_error Class
Example
Throw a logic_error when start is larger than end:
int start = 8;
int end = 3;
try {
if (start > end) {
throw logic_error("start cannot be larger than end");
}
cout << "From " << start << " to " << end;
} catch (const logic_error& e) {
cout << e.what();
}
Definition and Usage
A logic_error reports a mistake in the logic of the program, for example when the program breaks one of its own rules. These errors can be found before the program runs, by reading the code or by checking the values.
It is the parent class of domain_error, invalid_argument, length_error and out_of_range. Use logic_error when none of them fits.
The logic_error class is defined in the <stdexcept> header file.
Tip: catch (const logic_error& e) also catches all the classes that come from logic_error, like out_of_range.
Syntax
throw logic_error(message);
Catch it with catch (const logic_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 logic_error object. Its what() function returns the message. |
|---|
Related Pages
Read more about exceptions in our Exceptions Tutorial.