Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 788
fish2000 Avatar asked Jan 20 '16 18:01

fish2000


People also ask

What is a try-catch block?

What Does Try/Catch Block Mean? "Try" and "catch" are keywords that represent the handling of exceptions due to data or coding errors during program execution. A try block is the block of code in which exceptions occur. A catch block catches and handles try block exceptions.

Can we use try-catch in catch block?

Yes, we can declare a try-catch block within another try-catch block, this is called nested try-catch block.

Does C++ have try-catch finally?

The try-finally statement is a Microsoft extension to the C and C++ languages that enable target applications to guarantee execution of cleanup code when execution of a block of code is interrupted. Cleanup consists of such tasks as deallocating memory, closing files, and releasing file handles.

What is the use of finally block in exception handling in C++?

The purpose of the finally block is to clean up any resources left after the exception occurred. Note that the finally block is always executed, even if no exception was thrown. The catch block is only executed if a managed exception is thrown within the associated try block.


2 Answers

Yes, it will do exactly what you want: First release the RAII resource and then process the exception block.

like image 182
Mark B Avatar answered Sep 19 '22 06:09

Mark B


"… 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.

like image 45
πάντα ῥεῖ Avatar answered Sep 18 '22 06:09

πάντα ῥεῖ