C++ exceptions provide a mechanism for reporting errors in a thread-safe manner, without the need to manually unwind the call stack, while also providing support for RAII and complex data types. To better understand this, refer to the following example:
#include <cstring>
#include <iostream>
void myfunc(int val)
{
if (val == 42) {
throw EINVAL;
}
}
int main()
{
try {
myfunc(1);
std::cout << "success\n";
myfunc(42);
std::cout << "success\n";
}
catch(int ret) {
std::cout << "failure: " << strerror(ret) << '\n';
}
}
// > g++ -std=c++17 scratchpad.cpp; ./a.out
// success
// failure: Invalid argument
In the preceding example, our myfunc() function has been greatly simplified compared to its POSIX-style equivalent...