Simulating try/finally in plain C++ (without the C++/CLI extensions)

Dan wrote:

I think this is close enough to try/finally in C++:

Resource* pRes = new Resource;
  // use the allocated resource somehow
catch (...)
  delete pRes;

First, note that this code as written doesn't do "finally," because the idea behind a finally block is that it gets executed whether an exception is thrown or not. But it's close: You can indeed get a similar effect if you add a throw statement (e.g., throw 1;) at the end of your try block, so that it always exits via an exception, and then catch(...).

Even after applying the quick fix to make this do what was intended, this (ab)use of the try/catch mechanism inferior to having finally (or better still, in most cases, a destructor) because it interacts poorly with other exceptions. For example, what if other parts of the body could throw specific exceptions we want to catch? It would be repetitive and fragile to duplicate the delete statement in every catch block. Also, it's going to be more expensive in runtime cost because an exception will always be thrown, and actually throwing an exception has nonzero cost on every implementation I've heard of; having finally just has the compiler ensure the given code runs in all cases without having to throw an extra exception if none was otherwise being thrown.