C++ provides a robust mechanism for error handling using exceptions. By using the `throw` keyword, you can signal the occurrence of an error, while the `try` block allows you to attempt a block of code that may lead to an exception, and the `catch` block enables you to handle those exceptions effectively.
To throw an exception, you use the throw
keyword followed by an object that represents the exception. This object can be a built-in type or a user-defined type.
To catch an exception, you use a try
block followed by one or more catch
blocks that specify the different types of exceptions you want to handle.
#include
#include
void testFunction(int x) {
if (x < 0) {
throw std::invalid_argument("Negative value error");
}
std::cout << "Value: " << x << std::endl;
}
int main() {
try {
testFunction(-1);
} catch (const std::invalid_argument& e) {
std::cerr << "Caught an exception: " << e.what() << std::endl;
}
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?