In desperate circumstances, if one Exception needs to be converted into another, the Throwable.initCause(..) method is a way of remembering what the original Exception was – for debugging purposes only.  The getCause() of an exception should generally never be used to control program flow.

catch (DuplicateRecordException e)
    logger.error(“Problem creating record with name “ + name  
               + ':' + e.getMessage(), e);
    Exception stateException = new IllegalStateException();
    throw stateException;

The result of Throwable.getCause() on an exception should generally not be used as a means of program flow except when sending exceptions over networks (eg. EJBs).  In fact, this facility should be carefully used, if all, since most developers will not expect an exception to carry an inner payload.

Tip: Most exceptions have no need to contain a cause.  It can add unwanted noise to stack traces.

blog comments powered by Disqus