C++ stdexcept overflow_error Class
Example
Throw an overflow_error when the sum of two numbers is too big for an int:
int a = 2000000000;
int b = 2000000000;
try {
if (a > INT_MAX - b) {
throw overflow_error("The result is too big for an int");
}
cout << a + b;
} catch (const overflow_error& e) {
cout << e.what();
}
Definition and Usage
An overflow_error reports that the result of a calculation is too big for its data type.
INT_MAX (from <climits>) is the largest value an int can store. The program checks if a > INT_MAX - b before it adds the numbers, because the addition itself would overflow and give a wrong result.
The overflow_error class is defined in the <stdexcept> header file.
Tip: For a result that is too close to 0, use underflow_error.
Syntax
throw overflow_error(message);
Catch it with catch (const overflow_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: | An overflow_error object. Its what() function returns the message. |
|---|
Related Pages
Read more about exceptions in our Exceptions Tutorial.