views:

98

answers:

4

Suppose that I have a legacy java application with thousands of lines of code which do:

try {
   // stuff 
} catch (Exception e) {
   // eat the exception
}

Is there any global option that I could flip or 3rd party JAR which would log all "eaten" exceptions? I know that I could do a massive find replace (search for catch (Exception e) { and replace it with catch(Exception e) { logException(e);) but I was wondering if there was a better solution. Thanks!

A: 

No. If the code catches the exception and does nothing with it, then there's nothing you can do to change that without changing the code.

A find-replace should work. However, I would also strongly recommend checking it with FindBugs afterward to make sure that you found all instances of this problem. (FindBugs should be a part of your process anyway, but I'm just pointing it out in case anyone who reads this doesn't already use it.)

Michael Myers
Aspect Oriented Programming would let you log exceptions without changing the original code, as Rob Di Marco noted in his answer (http://stackoverflow.com/questions/2820259/globally-log-catch-exception-e/2820381#2820381).
markusk
@markusk: Point taken; there are actually several ways to do it. I've left this answer up mainly for the FindBugs part.
Michael Myers
@mmyers: In that case, why not delete the first paragraph of your answer? Your recommendation of FindBugs is still useful.
markusk
+6  A: 

You could perhaps provide your own implementation of Exception which logs the stack-trace in the constructor. From the man page of java:

-Xbootclasspath:bootclasspath
Specify a colon-separated list of directories, JAR archives, and ZIP archives to search for boot class files. These are used in place of the boot class files included in the Java 2 SDK.

aioobe
+1 that's an interesting idea.
Finbarr
I like it. It's sneaky, and it just might work.
Michael Myers
A: 

This will allow you to handle any uncaught exceptions:

Thread.setDefaultUncaughtExceptionHandler(
  new Thread.UncaughtExceptionHandler(){
    public void uncaughtException(Thread t, Throwable e) {
      //handle the exception
    }
});
Michael Angstadt
But that's not what he asks for.
aioobe
-1 for answering a different question.
DJClayworth
Good answer to the wrong question. The exceptions the OP is dealing with are caught, not uncaught
Chris Knight
+5  A: 

Seems like a place where Aspect Oriented Programming could come in handy. You could set up an exception handler pointcut. Check out AspectJ for a nice AOP implementation.

Rob Di Marco
Interesting Idea...
JoeGeeky