How to get the root exception of any exception

Sometimes, the root exception causing your code to fail is hidden behind an other exception or a set of nested exceptions.

Nested Exceptions

Nested Exceptions

 

The following code (function) searches for the root exception of any exception and returns it :

public static Throwable getRootException(Throwable exception){
 Throwable rootException=exception;
 while(rootException.getCause()!=null){
  rootException = rootException.getCause();
 }
 return rootException;
}

Example of usage :

catch(MyException e){
  System.out.println(getRootException(e).getLocalizedMessage());
}