Catching an exception that is nested into another exception

user321068 picture user321068 · Jun 2, 2010 · Viewed 66.2k times · Source

I want to catch an exception, that is nested into another exception. I'm doing it currently this way:

} catch (RemoteAccessException e) {
    if (e != null && e.getCause() != null && e.getCause().getCause() != null) {
        MyException etrp = (MyException) e.getCause().getCause();
        ...
    } else {
        throw new IllegalStateException("Error at calling service 'service'");
    }
}

Is there a way to do this more efficient and elegant?

Answer

user321068 picture user321068 · Sep 16, 2011

The ExceptionUtils#getRootCause() method can come in very handy in such situations.