C++ stdexcept runtime_error Class
Example
Throw a runtime_error when a file is not found:
bool fileFound = false;
try {
if (!fileFound) {
throw runtime_error("Could not find the file");
}
cout << "Reading the file";
} catch (const runtime_error& e) {
cout << e.what();
}
Definition and Usage
A runtime_error reports a problem that happens while the program runs. These problems often come from outside the program, like a file that is missing, or a network connection that is lost. The program cannot know about them before it runs.
It is the parent class of overflow_error, range_error and underflow_error. Use runtime_error when none of them fits.
The runtime_error class is defined in the <stdexcept> header file.
Tip: catch (const runtime_error& e) also catches all the classes that come from runtime_error, like overflow_error.
Syntax
throw runtime_error(message);
Catch it with catch (const runtime_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 runtime_error object. Its what() function returns the message. |
|---|
Related Pages
Read more about exceptions in our Exceptions Tutorial.