Is there a favored idiom for mimicing Java's try/finally in C++?

前端 未结 15 772
无人及你
无人及你 2021-02-05 19:16

Been doing Java for number of years so haven\'t been tracking C++. Has finally clause been added to C++ exception handling in the language definition?<

15条回答
  •  抹茶落季
    2021-02-05 19:36

    I think that you are missing the point of what catch (...) can do.

    You say in your example "alas, can't examine the exception". Well, you have no information about the type of the exception. You don't even know if it's a polymorphic type so even if you had some sort of an untyped reference to it, you couldn't even safely attempt a dynamic_cast.

    If you know about certain exceptions or exception hierarchies that you can do something with then this is the place for catch blocks with explicity named types.

    catch (...) is not often useful in C++. It can be used in places which have to guarantee that they don't throw, or only throw certain contracted exceptions. If you are using catch (...) for cleanup then there is a very good chance that your code is not robustly exception safe in any case.

    As mentioned in other answers, if you are using local objects to manage resources (RAII) then it can be surprising and enlightening how few catch blocks you need, often - if you don't need to do anything locally with an exception - even the try block can be redundant as you let the exceptions flow out to the client code that can respond to them while still guaranteeing no resource issues.

    To answer your original question, if you need some piece of code to run at the end of a block, exception or no exception, then a recipe would be.

    class LocalFinallyReplacement {
        ~LocalFinallyReplacement() { /* Finally code goes here */ }
    };
    // ...
    { // some function...
        LocalFinallyReplacement lfr; // must be a named object
    
        // do something
    }
    

    Note how we can completely do away with try, catch and throw.

    If you had data in the function that was originally declared outside the try block that you needed access to in the "finally" block, then you may need to add that to the constructor of the helper class and store it until the destructor. However, at this point I would seriously reconsider whether the problem could be resolved by altering the design of the local resource handling objects as it would imply something awry in the design.

提交回复
热议问题