Try finally in C++
Posted March 12th, 2005 . No Comments .
As you know C++ doesn’t have a finally block as most of the newer languages have. But with the code bellow you can simulate similar behavior, I have found is use full in some occasions.
#include <exception> #include <iostream> #define __finally catch( ... ) #define __leave throw detail::leave_exception() namespace detail { struct leave_exception: std::exception { leave_exception(): std::exception() { } }; } void func() { bool ok = false; try { if(!ok) __leave; } __finally { std::cout << "cleaning up" << std::endl; } } int main(int argc, char* argv[]) { func(); return 0; }
