Sunday, November 11, 2012

Nailing the Root Cause in Java Exceptions

Java provides chained exception facility which enables to nest an exception within another .But to get the deepest level exception,there are no direct methods available as of now.
Packages like  Apache's common lang provides convenience method to  get the root cause.
(http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/exception/ExceptionUtils.html)
The root cause can also be retrieved by manually iterating down the stack trace using getCause().
The following snippet is a recursive method that is used to retrieve the Root Cause.

public Throwable getMostSpecificException( Throwable exp ) { 
        Throwable t = exp;
        logger.debug( "exp.getMessage()-->" + exp.getMessage(  ) );
        if ( exp.getCause(  ) != null ) {
            t = exp.getCause(  );
            // recursive call
            getMostSpecificException( t );
        }
        return t;
    }