Woozle Wuzzle
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?

Comments
Post a comment













Remember personal info?






Creative Commons License Unless otherwise expressly stated, all original material of whatever nature created by Rob Grzywinski and included in this weblog and any related pages, including the weblog's archives, is licensed under a Creative Commons License.