C++ stdexcept domain_error Class
Example
Throw a domain_error before you find the square root of a negative number:
double x = -4;
try {
if (x < 0) {
throw domain_error("Cannot find the square root of a negative number");
}
cout << sqrt(x);
} catch (const domain_error& e) {
cout << e.what();
}
Definition and Usage
A domain_error reports that a value is outside the domain of a math function. The domain is all the values that the function works for.
For example, no normal number gives a negative result when you multiply it by itself. So a negative number, like -4, is outside the domain of the square root.
The domain_error class is defined in the <stdexcept> header file.
Note: The math functions in <cmath> do not throw domain_error. For example, sqrt() of a negative number returns NaN (not a number). This is why you check the value yourself, and throw the error.
Syntax
throw domain_error(message);
Catch it with catch (const domain_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 domain_error object. Its what() function returns the message. |
|---|
Related Pages
Read more about exceptions in our Exceptions Tutorial.