Connecting Tech Pros Worldwide Help | Site Map

cleanup and rethrow

  #1  
Old November 16th, 2006, 09:25 PM
Jason S
Guest
 
Posts: n/a
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;
}

  #2  
Old November 16th, 2006, 09:45 PM
David Golightly
Guest
 
Posts: n/a

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 Threads
Thread Thread Starter Forum Replies Last Post
throw from c'tor Chameleon answers 24 November 13th, 2006 08:25 PM
Unmanaged pointer cleanup in Managed class Maxwell answers 4 November 21st, 2005 11:05 PM
Exceptions and performance hit RepStat answers 6 November 16th, 2005 03:18 AM
C++: rethrow in exception handling A answers 5 July 22nd, 2005 04:28 AM