C++ stdexcept exception Class
Example
Catch an out_of_range error as an exception:
try {
throw out_of_range("The index is too big");
} catch (const exception& e) {
cout << "Error: " << e.what();
}
Definition and Usage
The exception class is the parent class (base class) of all the standard exceptions, like runtime_error, logic_error and out_of_range. When you catch exception, you catch all of them with one catch block.
Always catch it by reference (with &). If you catch it without &, the program makes a copy that only has the exception part, and what() no longer returns your message.
The exception class is defined in the <exception> header file.
Note: The exception class has no constructor that takes a message. To throw an error with a message, use one of the classes in <stdexcept>, like runtime_error.
Syntax
try {
// code that can throw an exception
} catch (const exception& e) {
// code that handles the error
}
Parameter Values
| Parameter | Description |
|---|---|
| e | Optional. A name for the caught exception. You need it to call e.what(). |
Technical Details
| Returns: | The caught object is of a class that comes from exception, like out_of_range. Use what() to get its message. |
|---|
Related Pages
Read more about exceptions in our Exceptions Tutorial.