Note that there are some explanatory texts on larger screens.

plurals
  1. POIs there a favored idiom for mimicing Java's try/finally in C++?
    primarykey
    data
    text
    <p>Been doing Java for number of years so haven't been tracking C++. Has <strong><em>finally</em></strong> clause been added to C++ exception handling in the language definition?</p> <p>Is there a favored idiom that mimics Java's try/finally?</p> <p>Am also bothered that C++ doesn't have an ultimate super type for all possible exceptions that could be thrown - like Java's Throwable class.</p> <p>I can write:</p> <pre><code>try { // do something } catch(...) { // alas, can't examine the exception // can only do cleanup code and perhaps rethrow, ala: throw; } </code></pre> <p><strong>ADDENDUM EDIT:</strong></p> <blockquote> <p>I ended up accepting the answer that had the most up votes, i.e., use destructors to do cleanup. Of course, from my own comments, it is clear I don't entirely agree with that. However, C++ is what it is and so in the application endeavor I have in mind, I'm going to more or less strive to adhere to common community practice. I'll use template classes to wrap resources that don't already have a class destructor (i.e., C library resources), thus bestowing on them destructor semantics.</p> </blockquote> <p><strong>NEW ADDENDUM EDIT:</strong></p> <blockquote> <p>Hmm, instead of <strong><em>finally</em></strong> then a closure feature perhaps? A closure combined with ScopeGuard approach (see one of the answers below) would be a way to accomplish cleanup with arbitrary actions and access to the cleanup code's outer scope context. Cleanup could be done in the idiom fashion that is seen in Ruby programming where they supply cleanup blocks when a resource is being opened. Isn't a closure feature being considered for C++?</p> </blockquote>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload