What happens if I don't catch a throw?

Yes, that's how exceptions work. When an exception is thrown, it is caught by the topmost function in the call stack that has a handler for that exception in the scope of execution. Since you are going back to a function lower in the stack, some variables in the scope of the functions in the upper stack frames need to get out of scope, and therefore their destructors are called. This is called stack unwinding. It is really nice to combine that and RAII (lookup RAII if you don't know what that is). However, If any destructor throws an exception during stack unwinding, then it is bad and the std::terminate function will be called. Typically your program will then end (and this is why you are always advised to write non-throwing destructors).

From cppreference.com:

Once the exception object is constructed, the control flow works backwards (up the call stack) until it reaches the start of a try block, at which point the parameters of the associated catch blocks are compared with the thrown expression to find a match. If no match is found, the control flow continues to unwind the stack until the next try block, and so on. If a match is found, the control flow jumps to the matching catch block (the exception handler), which executes normally.

As the control flow moves up the call stack, destructors are invoked for all objects with automatic storage duration constructed since the corresponding try-block was entered, in reverse order of construction. If an exception is thrown from a constructor, destructors are called for all fully-constructed non-static non-variant members and base classes. This process is called stack unwinding.


Since function2() and function1() don't catch the exception it will propagate up the call stack until it is caught by the first suitable handler which you have in main(). Local objects destructors are being called along the way which is called stack unwinding. If you didn't have a suitable handler the C++ runtime would call unexpected() built-in function that would call abort() and terminate the program.


Yes, but it doesn't get "rethrown" - simply, when you throw an exception it will walk the call stack until it can find a catch block that can handle it; this is one of the most important "selling points" of exceptions.

If no suitable handler is found, std::terminate is called and your program terminates abnormally (notice that in this case it's not guaranteed that destructors will be called).

Tags:

C++