Search code examples
c++exceptiontry-catchraiinoexcept

Are C++ `try`/`catch` blocks the same as other blocks, regarding RAII?


OK so if I am using a RAII idiom to manage some context attribute*, will it work as I expect if I use it nakedly in at the start of a try block?

In other words, if I have this:

struct raii {
    raii() {
        std::cout << "Scope init"
                  << std::endl; }
    ~raii() {
        std::cout << "Scope exit"
                  << std::endl; }
};

… and I am successfully using it like this:

{
    raii do_the_raii_thing;
    stuff_expecting_raii_context();
    /* … */
}

… will the RAII instance work the same way if I do this:

try {
    raii do_the_raii_thing;
    stuff_expecting_raii_context_that_might_throw();
    /* … */
} catch (std::exception const&) {
    /* … */
}

This is probably a dumb question, but I want to check my own sanity on this – I am fuzzy on the subtleties of noexcept guarantees, and other exception-related minutiae – so pardon my naíveté


[*] for those curious, it’s the Python C-API’s nefarious GIL (global interpreter lock) that I am managing with RAII, in my specific case


Solution

  • "… will the RAII instance work the same way if I do this: ..."

    Sure they will. The RAII instance will go out of scope and the destructors are called before the catch, if an exception is thrown.

    Also this will work for any upper levels, that are calling your function if you just throw and there aren't any try/catch blocks. That's called stack unwinding.