Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try catch finally construct - is it in C++11? [duplicate]

Tags:

c++

c++11

Possible Duplicate:
Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

Does try/catch/finally construct is supported in C++11?
I'm asking because I couldn't find anywhere information about it. Thanks.

like image 259
smallB Avatar asked Oct 15 '11 18:10

smallB


People also ask

What is finally in try catch?

The code opens a file and then executes statements that use the file; the finally -block makes sure the file always closes after it is used even if an exception was thrown.

What is the difference between try catch block and try finally block?

The try statement defines the code block to run (to try). The catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result. The throw statement defines a custom error.

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.

Is finally always run C#?

A finally block always executes, regardless of whether an exception is thrown.


1 Answers

Not an excuse to forgo RAII, but useful when e.g. using non RAII aware APIs:

template<typename Functor>
struct finally_guard {
    finally_guard(Functor f)
        : functor(std::move(f))
        , active(true)
    {}

    finally_guard(finally_guard&& other)
        : functor(std::move(other.functor))
        , active(other.active)
    { other.active = false; }

    finally_guard& operator=(finally_guard&&) = delete;

    ~finally_guard()
    {
        if(active)
            functor();
    }

    Functor functor;
    bool active;
};

template<typename F>
finally_guard<typename std::decay<F>::type>
finally(F&& f)
{
    return { std::forward<F>(f) };
}

Usage:

auto resource = /* acquire */;
auto guard = finally([&resource] { /* cleanup */ });
// using just
// finally([&resource] { /* cleanup */ });
// is wrong, as usual

Note how you don't need a try block if you don't need to translate or otherwise handle exceptions.

While my example makes use of C++11 features, the same generic functionality was available with C++03 (no lambdas though).

like image 101
Luc Danton Avatar answered Oct 04 '22 20:10

Luc Danton