Tip #5 of my blog post Ten Tips for Using Java Stack Traces demonstrates two example of using Java code to extract a Throwable's (implying Error or Exception) stack trace into a single String representation using either PrintWriter or PrintStream. These are not difficult to implement, but must be implemented for every code base in which it is desirable to get a String representing the entire stack trace. For a program that is already using Guava for other niceties it provides, a nice alternative is to use Guava's Throwables class and to specifically use its aptly named getStackTraceAsString(Throwable) method to extract a String
from a provided Throwable
.
The Javadoc documentation describes how simple it is to use this method:
Returns a string containing the result of toString(), followed by the full, recursive stack trace of throwable. Note that you probably should not be parsing the resulting string; if you need programmatic access to the stack frames, you can call Throwable.getStackTrace().
The Javadoc points out that this String should not be used for programmatic access of the stack trace. Instead, StackTraceElements should be accessed and manipulated from Throwable.getStackTrace() as I discussed in The Surprisingly Simple StackTraceElement.
Guava's Throwables class has other useful methods for dealing with Java's Exceptions and Errors as well. There are multiple methods for propagating Throwables based on certain conditions and there are methods for more precise control of chained exceptions. For example, Throwables.getRootCause(Throwable) returns the exception that is often most important (see Tips #2 and #3 in Ten Tips for Using Java Stack Traces) in a chain (the "innermost" or "first throwable" in the chain) from a provided Throwable. Another example is the method Throwables.getCausalChain() that presents the chained Throwables in a Java List.
I probably would not include Guava in a project solely to extract Throwable stack traces into Strings because I could write my own static method with a few lines of code to do the same thing and put that in a utilities or common package in my code base. However, if I'm using Guava anyway for other reasons and including it in my dependencies, then it is preferable to use the Guava-provided functionality rather than rolling out my own that others need to be made aware of and learn about.
No comments:
Post a Comment