Is it reasonable to maintain a reference to an exception for later use, or are there pitfalls involved with keeping a reference to an exception for significantly longer than the throw/catch interaction?
For example, given the code:
class Thing {
private MyException lastException = ...;
synchronized void doSomethingOrReportProblem() {
try {
doSomething();
} catch (MyException e) {
if (seemsLikeADifferentProblem(e, lastException)) {
reportProblem(e);
}
lastException = e;
}
}
}
Assuming that my program creates a Thing with a lifespan as long as the JVM, are there any correctness issues involved with Thing maintaining a lingering reference to lastException? And has this changed at all in JDK7? (Looking at the source code to Throwable in OpenJDK7, it seems like there’s a new four-argument public constructor that wasn’t in JDK6 that can create a Throwable without invoking fillInStackTrace() at construction time.)
If any of the chained exceptions under MyException had references to objects, yes, this would prevent those objects from getting garbage collected, but assuming I’m ok with that, are there any traps to beware?
A Throwable is a full-fledged Java object and will persist as long as someone has a reference to it. It’s been awhile since I was inside Throwable, but I can’t think of anything it might in turn be retaining a reference to other than (just maybe) the classes of the methods in the stack trace. The stack trace itself does consume a non-trivial amount of storage, however.
So it’s really no different from any other moderately large object. And retaining a single exception for the life of the JVM would not seem to be at all out of line. (If you kept a record of ALL exceptions, that might be a bit much.)