Understanding exception support in C++

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. ...

Get Hands-On System Programming with C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.