C++ std::exception is a standard library that provides a mechanism for reporting and handling errors in a C++ program. It defines a common base class for all exception types and provides several derived classes for different types of errors.
One of the examples of using the std::exception is:
In this example, we threw an instance of `std::logic_error` exception in the try block. The `what()` function is called to get the error message, which is then displayed to the user in the catch block.
Another example is:
c++
#include
#include
#include
int main() {
try {
std::vector v{1, 2, 3, 4, 5};
std::cout << v.at(10) << std::endl; // this will throw std::out_of_range
} catch(const std::out_of_range& e) {
std::cerr << "Out of range error: " << e.what() << std::endl;
} catch(const std::exception& e) {
std::cerr << "Error occurred: " << e.what() << std::endl;
}
return 0;
}
```
In this example, we use the `at()` function to access an element of a vector at an invalid index, which will throw an `std::out_of_range` exception. We catch this specific exception type in the catch block and handle it accordingly.
The std::exception library is part of the C++ Standard Library.
C++ (Cpp) exception - 30 examples found. These are the top rated real world C++ (Cpp) examples of std::exception extracted from open source projects. You can rate examples to help us improve the quality of examples.