I haven't used try/catch/finally very much in Javascript. My function
(let's call it try_it()) needs to call a function that could throw an
exception (let's call it dangerous()) with some setup() beforehand and
cleanup() afterwards. What I want to make sure cleanup() is called
whether or not dangerous throws an exception, and if it does throw an
exception, rethrow the exception to whatever is calling try_it().
In C++ this is much easier because you can make setup/cleanup a
constructor/destructor pair and the compiler takes care of it whether
or not you have an exception.
I'm not quite sure how to do this; the following seems to work, with
the only downside being that I have to include two references to
cleanup(). Is there a more elegant way that would use finally or
something?
function try_it(x)
{
var rv;
setup();
try {
rv = dangerous(x);
} catch (e)
{
cleanup();
throw(e);
}
cleanup();
return rv;
}