The 'throw' keyword can be used to rethrow an exception that has already modified program flow.   The main use of the try/catch/rethrow technique is to only allow through exceptions that can be handled by calling code.

For example, a piece of code might throw a ValidationException which is OK, but any others are a problem.  The developer might choose to catch ValidationException and rethrow it, and catch any other Exception to deal with as a serious error.

..just rethrow the existing exception.

try
{
    :
}
catch(ValidationException e)
{
    throw e;
}
catch(Exception e)
{
    throw new UnexpectedError(“Could not store record”,e);
}

Tip: There is no reason to construct a new exception if there is already one of the same type, as in the following example:

try
{
    :
}
catch(ValidationException e)
{
    throw new ValidationException(e.getMessage());
}
:

Rethrow activity is often incorrectly used, replacing finally blocks or to work around poorly structured exception trees.

protected void reprocess() throws Exception
{
    try
    {
        openStreams();
        :
    }
    catch(Exception e)
    {
        if (e.getMessage().toLowerCase().contains("processing"))
        {
            throw e;
        }
    }
    finally
    {
        closeStreams();
    }
}

Creating specific exception types will solve this problem, so the generic exception catch would be better written:

protected void reprocess() throws ProcessingException
{
    try
    {
        openStreams();
        :
    }
    catch(ProcessingException e)
    {
   // exception is correct type to begin with – rethrow it
        // because the application can recover from this problem
        throw e;
    }
    catch(Exception e)
    {
        // can't continue.
        logger.error(e);
        throw new FailedProcessingException(“Reprocess fail”, e);
    }
    finally
    {
        closeStreams();
    }
 }
blog comments powered by Disqus