Connecting Tech Pros Worldwide Forums | Help | Site Map

cleanup and rethrow

Jason S
Guest
 
Posts: n/a
#1: Nov 16 '06
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;
}


David Golightly
Guest
 
Posts: n/a
#2: Nov 16 '06

re: cleanup and rethrow



Jason S wrote:
Quote:
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;
}

Then you want finally:

try {
dangerous();
} catch(ex) {
handle(ex);
throw(ex);
} finally {
cleanup();
}


test:

try {
dangerous();
} catch(ex) {
alert('caught');
throw(ex);
} finally {
alert('cleaning up');
}

finally gets called whether or not an exception occurred, regardless of
whether you re-throw the exception. It basically always gets called no
matter what.

Closed Thread


Similar JavaScript / Ajax / DHTML bytes