In wikipedia we read:
Resource Acquisition Is Initialization RAII is a programming idiom used in several object-oriented languages like C++, D, Ada and Vala. The technique was invented by Bjarne Stroustrup to deal with resource allocation and deallocation in C++. In this language, the only code that can be guaranteed to be executed after an exception is thrown are the destructors of objects residing on the stack.
I don't want to be over pedantic, whatever, but I really am not sure how to interpret this. Is this a slip of the tongue or is this correct? Aren't catch
handlers guaranteed to be executed at least?
I know about RAII and what it is, I am focused here on this only code that can be guaranteed to be executed (..) are destructors of objects residing on the stack.
Strictly speaking, the quote is already wrong. When an exception is thrown and there's no matching handler for it, terminate
can be called without unwinding the stack and calling any destructors. So, the statement that says that "destructors are guaranteed to be executed when an exception is thrown" is wrong.
As for catch
handlers themselves, of course, it is only possible to execute a catch
handler if the matching catch handler actually exists.
On top of that, even if the handler exists, there are other reasons that can throw a spanner in the works and prematurely terminate the processing of the exception before it reaches the catch
handler. For example, it happens when an "unexpected" exception is thrown. If your function exception specification prohibits some specific exception type and an exception of such "prohibited" type attempts to "fly out" of that function, unexpected
will be called immediately, instead of transferring control to the handler.
As mentioned in the comments, another typical situation is when new exception is thrown during stack unwinding triggered by a previous exception. This will result in terminate
being called.