Have you hugged your StackTraceElement today?

More J2SE revelations today as I discovered the method, StackTraceElement[] Throwable.getStackTrace(), introduced in J2SE 1.4. So what’s a StackTraceElement? Essentially, everything you’ve been seeing in a line of a printed stack trace for years – class name, method name, line number, and a convenient toString() method that returns the link you’re used to seeing in your traces.

Clearly, this sort of information has been hidden somewhere for years, kudos to the folks that put this into the spec for exposing to developers. I can think of a lot of things this could be abused – some people might use the source of the exception in place of error codes in designing how they handle the exception (if traceElement.getClassName, or worse, lineNumber == “com.moron.App” then handle one way, else handle another). One scenario that comes to my mind is for tracking down bugs. Suppose you have an Exception that’s unexpectedly being thrown at infrequent intervals, but when it happens you want to give it immediate attention, and suppose it’s a commmon exception type. Rather than changing your code, you could write an AOP interceptor that traps that common exception, checks if the source of that exception was the problem spot, and takes some notification action (perhaps logging to an SMTP log appender or something). I’d be curious what scenarios others more familiar with this distant corner of Java have done

Are you going to use this every day, week, or month? Not at all. But I’m thinking it’s a handy thing to keep in the back of your mind.


One thought on “Have you hugged your StackTraceElement today?

  1. I have used it in the past for debugging purposes while trying to solve some pretty bad bugs. Other then that it is convenient for filtering of what parts of the stack trace you want to see. Log space is cheap but sometimes if you can filter on the output it helps in weeding through the logs during production issues.

    Not sure I would tell a lot of people about it though. It seems it could be pretty dangerous in the wrong hands. Some people might use it for a java GOTO style programming for the business logic. If the stack trace contains “com.blah.logic” go to another object and call a method.

    The aspect technique might be an idea as well. Just aspect a filter if you needed it.

Comments are closed.