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.