C++ exceptions provide a way to return an error to a catch handler somewhere in the call stack. We will cover C++ exceptions in great detail in Chapter 13, Error - Handling with Exceptions.
For now, we will work with the following simple example:
#include <iostream>#include <exception>void test(int i){ if (i == 42) { throw 42; }}int main(void){ try { test(1); std::cout << "attempt #1: passed\n"; test(21); std::cout << "attempt #2: passed\n"; } catch(...) { std::cout << "exception catch\n"; }}// > g++ scratchpad.cpp; ./a.out// attempt #1: passed// exception catch
In the previous example, we create a simple test() function that takes an input. If the input is equal to 42, we throw an exception. This will cause ...