Setting a flag in the case of an exception

There are a number of cases where something needs to be done only in the case where an exception is thrown (checked or not). A first pass on this would look like:

...
// allow the user to do something.  If it fails for any reason
// the error flag must be set so that further operations are not
// attempted.
try
{
doSomething();
} catch(final Throwable t)
{
// some exception has been thrown; set the error flag.
error = true;
// continue the exception
throw t;
}
...

The problem with this is that unless the method signature includes throws Throwable you’re out of luck. To circumvent this, I do the following:

...
// allow the user to do something.  If it fails for any reason
// the error flag must be set so that further operations are not
// attempted.
boolean exceptionThrown = true; // set to false -only- if successful
try
{
doSomething();
// no exceptions were thrown
exceptionThrown = false;
} finally
{
// if there was an exception thrown (exceptionThrown will have
// been set to false if an exception was -not- thrown) then set
// the error flag.
if(exceptionThrown)
error = true;
/* else -- there was no exception thrown */
}
...

Are there any better techniques out there or is this acceptable?

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s