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.
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.
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.
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.
A finally block always executes, regardless of whether an exception is thrown.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With