Tag: Exceptions

Is StackWalker Useful?

In Java 9, Oracle plans to introduce the StackWalker class and API.

The old way (since Java 1.4) of getting stack trace info was to call:

StackTraceElement[] stackTrace = new Throwable().getStackTrace();

The new API provides more choices with a stream-based API. To do roughly the same thing as the old example, you’d call:

List<StackFrame> stack = StackWalker.getInstance().walk(s -> s.collect(Collectors.toList()));

It’s cleaner to be able to get stack trace information without having to create an otherwise superfluous Throwable object, and the new API facilitates recovering the Class object, rather than just the qualified class name.

However, there seems to have been no effort to retrofit Throwable for the new API. Most of the time, it’s when we’re dealing with exceptions that we’re interested in stack traces. It would be nice to have a slick stream-based or builder API which allows better control over which stack frames are printed in the logs. This is especially important for Java EE, where the code you wrote is at times a needle in the haystack of layers of proxy calls and reflection. It is possible to create such an API in Java 8, though its slickness would be limited by the fact that it would need to be applied on top of existing Throwable and Exception classes (you’d have to call it just before logging the exception, perhaps making a deep clone of the original exception with altered stack frame elements). It would be nicer to be able to add a filtering predicate or a more complete object we might call a StackTracePrinter to the Exception object before logging.

So I’m not sure in what cases I’d actually use StackWalker. It could be useful for one-off diagnostics that never get committed to production. Also, in the debugger you have the full stack trace in the UI, but maybe it could be faster to walk the stack in the debugger to find certain targeted elements. I’m stretching it a bit, because I don’t see a lot of use cases. Feel free to add a comment if you have a great use case for StackWalker which is not possible pre-Java 9.