Learning about set jump exceptions

Set jump exceptions may be viewed as C-style exceptions. Like C++-style exceptions, set jump exceptions provide the user with the ability to set a place in the code to return to in the event of an error, and a method for generating the exception that performs the jump. The following code example demonstrates this:

#include <cstring>#include <csetjmp>#include <iostream>std::jmp_buf jb;void myfunc(int val){    if (val == 42) {        errno = EINVAL;   // Invalid argument        std::longjmp(jb, -42);    }}int main(){    if (setjmp(jb) == -42) {        std::cout << "failure: " << strerror(errno) << '\n';        std::exit(EXIT_FAILURE);    }    myfunc(1);    std::cout << "success\n";    myfunc(42);    std::cout << "success\n";}// > g++ -std=c++17 scratchpad.cpp; ...

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.