Guava Throwables Tutorial

Guava provides the Throwables class which contains a number of static utility methods to work with instances of Java Throwable. Exception handling is a common component in nearly all java programs and getting it correct and consistently printing out the right information can be tricky. Navigating stack traces is not always straightforward and extracting the relevant information is cumbersome. Thankfully, Throwables makes it much easier to print and extract the needed data.

Converting a Stack Trace to a String

The Throwables method getStackTraceAsString(Throwable throwable) returns the passed in Throwable object as a String. This is useful when logging or outputting exceptions to the command line, as it will include the location in the source code where the exception occurred.


try
{
   throw new NullPointerException("This is a null pointer exception");
}
catch(Exception e)
{
   System.out.println(Throwables.getStackTraceAsString(e));
}